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,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/Implementation/Classification/SemanticClassificationUtilities.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Classification { internal static class SemanticClassificationUtilities { public static async Task ProduceTagsAsync( TaggerContext<IClassificationTag> context, DocumentSnapshotSpan spanToTag, IClassificationService classificationService, ClassificationTypeMap typeMap) { var document = spanToTag.Document; if (document == null) return; // Don't block getting classifications on building the full compilation. This may take a significant amount // of time and can cause a very latency sensitive operation (copying) to block the user while we wait on this // work to happen. // // It's also a better experience to get classifications to the user faster versus waiting a potentially // large amount of time waiting for all the compilation information to be built. For example, we can // classify types that we've parsed in other files, or partially loaded from metadata, even if we're still // parsing/loading. For cross language projects, this also produces semantic classifications more quickly // as we do not have to wait on skeletons to be built. document = document.WithFrozenPartialSemantics(context.CancellationToken); spanToTag = new DocumentSnapshotSpan(document, spanToTag.SnapshotSpan); var classified = await TryClassifyContainingMemberSpanAsync( context, spanToTag, classificationService, typeMap).ConfigureAwait(false); if (classified) { return; } // We weren't able to use our specialized codepaths for semantic classifying. // Fall back to classifying the full span that was asked for. await ClassifySpansAsync( context, spanToTag, classificationService, typeMap).ConfigureAwait(false); } private static async Task<bool> TryClassifyContainingMemberSpanAsync( TaggerContext<IClassificationTag> context, DocumentSnapshotSpan spanToTag, IClassificationService classificationService, ClassificationTypeMap typeMap) { var range = context.TextChangeRange; if (range == null) { // There was no text change range, we can't just reclassify a member body. return false; } // there was top level edit, check whether that edit updated top level element var document = spanToTag.Document; if (!document.SupportsSyntaxTree) { return false; } var cancellationToken = context.CancellationToken; var lastSemanticVersion = (VersionStamp?)context.State; if (lastSemanticVersion != null) { var currentSemanticVersion = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false); if (lastSemanticVersion.Value != currentSemanticVersion) { // A top level change was made. We can't perform this optimization. return false; } } var service = document.GetLanguageService<ISyntaxFactsService>(); // perf optimization. Check whether all edits since the last update has happened within // a member. If it did, it will find the member that contains the changes and only refresh // that member. If possible, try to get a speculative binder to make things even cheaper. var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var changedSpan = new TextSpan(range.Value.Span.Start, range.Value.NewLength); var member = service.GetContainingMemberDeclaration(root, changedSpan.Start); if (member == null || !member.FullSpan.Contains(changedSpan)) { // The edit was not fully contained in a member. Reclassify everything. return false; } var subTextSpan = service.GetMemberBodySpanForSpeculativeBinding(member); if (subTextSpan.IsEmpty) { // Wasn't a member we could reclassify independently. return false; } var subSpan = subTextSpan.Contains(changedSpan) ? subTextSpan.ToSpan() : member.FullSpan.ToSpan(); var subSpanToTag = new DocumentSnapshotSpan(spanToTag.Document, new SnapshotSpan(spanToTag.SnapshotSpan.Snapshot, subSpan)); // re-classify only the member we're inside. await ClassifySpansAsync( context, subSpanToTag, classificationService, typeMap).ConfigureAwait(false); return true; } private static async Task ClassifySpansAsync( TaggerContext<IClassificationTag> context, DocumentSnapshotSpan spanToTag, IClassificationService classificationService, ClassificationTypeMap typeMap) { try { var document = spanToTag.Document; var snapshotSpan = spanToTag.SnapshotSpan; var snapshot = snapshotSpan.Snapshot; var cancellationToken = context.CancellationToken; using (Logger.LogBlock(FunctionId.Tagger_SemanticClassification_TagProducer_ProduceTags, cancellationToken)) { using var _ = ArrayBuilder<ClassifiedSpan>.GetInstance(out var classifiedSpans); await AddSemanticClassificationsAsync( document, snapshotSpan.Span.ToTextSpan(), classificationService, classifiedSpans, cancellationToken: cancellationToken).ConfigureAwait(false); foreach (var span in classifiedSpans) context.AddTag(ClassificationUtilities.Convert(typeMap, snapshotSpan.Snapshot, span)); var version = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false); // Let the context know that this was the span we actually tried to tag. context.SetSpansTagged(SpecializedCollections.SingletonEnumerable(spanToTag)); context.State = version; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private static async Task AddSemanticClassificationsAsync( Document document, TextSpan textSpan, IClassificationService classificationService, ArrayBuilder<ClassifiedSpan> classifiedSpans, CancellationToken cancellationToken) { var workspaceStatusService = document.Project.Solution.Workspace.Services.GetRequiredService<IWorkspaceStatusService>(); // Importantly, we do not await/wait on the fullyLoadedStateTask. We do not want to ever be waiting on work // that may end up touching the UI thread (As we can deadlock if GetTagsSynchronous waits on us). Instead, // we only check if the Task is completed. Prior to that we will assume we are still loading. Once this // task is completed, we know that the WaitUntilFullyLoadedAsync call will have actually finished and we're // fully loaded. var isFullyLoadedTask = workspaceStatusService.IsFullyLoadedAsync(cancellationToken); var isFullyLoaded = isFullyLoadedTask.IsCompleted && isFullyLoadedTask.GetAwaiter().GetResult(); // If we're not fully loaded try to read from the cache instead so that classifications appear up to date. // New code will not be semantically classified, but will eventually when the project fully loads. if (await TryAddSemanticClassificationsFromCacheAsync(document, textSpan, classifiedSpans, isFullyLoaded, cancellationToken).ConfigureAwait(false)) return; await classificationService.AddSemanticClassificationsAsync( document, textSpan, classifiedSpans, cancellationToken).ConfigureAwait(false); } private static async Task<bool> TryAddSemanticClassificationsFromCacheAsync( Document document, TextSpan textSpan, ArrayBuilder<ClassifiedSpan> classifiedSpans, bool isFullyLoaded, CancellationToken cancellationToken) { // Don't use the cache if we're fully loaded. We should just compute values normally. if (isFullyLoaded) return false; var semanticCacheService = document.Project.Solution.Workspace.Services.GetService<ISemanticClassificationCacheService>(); if (semanticCacheService == null) return false; var checksums = await document.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false); var checksum = checksums.Text; var result = await semanticCacheService.GetCachedSemanticClassificationsAsync( SemanticClassificationCacheUtilities.GetDocumentKeyForCaching(document), textSpan, checksum, cancellationToken).ConfigureAwait(false); if (result.IsDefault) return false; classifiedSpans.AddRange(result); return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Classification { internal static class SemanticClassificationUtilities { public static async Task ProduceTagsAsync( TaggerContext<IClassificationTag> context, DocumentSnapshotSpan spanToTag, IClassificationService classificationService, ClassificationTypeMap typeMap) { var document = spanToTag.Document; if (document == null) return; // Don't block getting classifications on building the full compilation. This may take a significant amount // of time and can cause a very latency sensitive operation (copying) to block the user while we wait on this // work to happen. // // It's also a better experience to get classifications to the user faster versus waiting a potentially // large amount of time waiting for all the compilation information to be built. For example, we can // classify types that we've parsed in other files, or partially loaded from metadata, even if we're still // parsing/loading. For cross language projects, this also produces semantic classifications more quickly // as we do not have to wait on skeletons to be built. document = document.WithFrozenPartialSemantics(context.CancellationToken); spanToTag = new DocumentSnapshotSpan(document, spanToTag.SnapshotSpan); var classified = await TryClassifyContainingMemberSpanAsync( context, spanToTag, classificationService, typeMap).ConfigureAwait(false); if (classified) { return; } // We weren't able to use our specialized codepaths for semantic classifying. // Fall back to classifying the full span that was asked for. await ClassifySpansAsync( context, spanToTag, classificationService, typeMap).ConfigureAwait(false); } private static async Task<bool> TryClassifyContainingMemberSpanAsync( TaggerContext<IClassificationTag> context, DocumentSnapshotSpan spanToTag, IClassificationService classificationService, ClassificationTypeMap typeMap) { var range = context.TextChangeRange; if (range == null) { // There was no text change range, we can't just reclassify a member body. return false; } // there was top level edit, check whether that edit updated top level element var document = spanToTag.Document; if (!document.SupportsSyntaxTree) { return false; } var cancellationToken = context.CancellationToken; var lastSemanticVersion = (VersionStamp?)context.State; if (lastSemanticVersion != null) { var currentSemanticVersion = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false); if (lastSemanticVersion.Value != currentSemanticVersion) { // A top level change was made. We can't perform this optimization. return false; } } var service = document.GetLanguageService<ISyntaxFactsService>(); // perf optimization. Check whether all edits since the last update has happened within // a member. If it did, it will find the member that contains the changes and only refresh // that member. If possible, try to get a speculative binder to make things even cheaper. var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var changedSpan = new TextSpan(range.Value.Span.Start, range.Value.NewLength); var member = service.GetContainingMemberDeclaration(root, changedSpan.Start); if (member == null || !member.FullSpan.Contains(changedSpan)) { // The edit was not fully contained in a member. Reclassify everything. return false; } var subTextSpan = service.GetMemberBodySpanForSpeculativeBinding(member); if (subTextSpan.IsEmpty) { // Wasn't a member we could reclassify independently. return false; } var subSpan = subTextSpan.Contains(changedSpan) ? subTextSpan.ToSpan() : member.FullSpan.ToSpan(); var subSpanToTag = new DocumentSnapshotSpan(spanToTag.Document, new SnapshotSpan(spanToTag.SnapshotSpan.Snapshot, subSpan)); // re-classify only the member we're inside. await ClassifySpansAsync( context, subSpanToTag, classificationService, typeMap).ConfigureAwait(false); return true; } private static async Task ClassifySpansAsync( TaggerContext<IClassificationTag> context, DocumentSnapshotSpan spanToTag, IClassificationService classificationService, ClassificationTypeMap typeMap) { try { var document = spanToTag.Document; var snapshotSpan = spanToTag.SnapshotSpan; var snapshot = snapshotSpan.Snapshot; var cancellationToken = context.CancellationToken; using (Logger.LogBlock(FunctionId.Tagger_SemanticClassification_TagProducer_ProduceTags, cancellationToken)) { using var _ = ArrayBuilder<ClassifiedSpan>.GetInstance(out var classifiedSpans); await AddSemanticClassificationsAsync( document, snapshotSpan.Span.ToTextSpan(), classificationService, classifiedSpans, cancellationToken: cancellationToken).ConfigureAwait(false); foreach (var span in classifiedSpans) context.AddTag(ClassificationUtilities.Convert(typeMap, snapshotSpan.Snapshot, span)); var version = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false); // Let the context know that this was the span we actually tried to tag. context.SetSpansTagged(SpecializedCollections.SingletonEnumerable(spanToTag)); context.State = version; } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private static async Task AddSemanticClassificationsAsync( Document document, TextSpan textSpan, IClassificationService classificationService, ArrayBuilder<ClassifiedSpan> classifiedSpans, CancellationToken cancellationToken) { var workspaceStatusService = document.Project.Solution.Workspace.Services.GetRequiredService<IWorkspaceStatusService>(); // Importantly, we do not await/wait on the fullyLoadedStateTask. We do not want to ever be waiting on work // that may end up touching the UI thread (As we can deadlock if GetTagsSynchronous waits on us). Instead, // we only check if the Task is completed. Prior to that we will assume we are still loading. Once this // task is completed, we know that the WaitUntilFullyLoadedAsync call will have actually finished and we're // fully loaded. var isFullyLoadedTask = workspaceStatusService.IsFullyLoadedAsync(cancellationToken); var isFullyLoaded = isFullyLoadedTask.IsCompleted && isFullyLoadedTask.GetAwaiter().GetResult(); // If we're not fully loaded try to read from the cache instead so that classifications appear up to date. // New code will not be semantically classified, but will eventually when the project fully loads. if (await TryAddSemanticClassificationsFromCacheAsync(document, textSpan, classifiedSpans, isFullyLoaded, cancellationToken).ConfigureAwait(false)) return; await classificationService.AddSemanticClassificationsAsync( document, textSpan, classifiedSpans, cancellationToken).ConfigureAwait(false); } private static async Task<bool> TryAddSemanticClassificationsFromCacheAsync( Document document, TextSpan textSpan, ArrayBuilder<ClassifiedSpan> classifiedSpans, bool isFullyLoaded, CancellationToken cancellationToken) { // Don't use the cache if we're fully loaded. We should just compute values normally. if (isFullyLoaded) return false; var semanticCacheService = document.Project.Solution.Workspace.Services.GetService<ISemanticClassificationCacheService>(); if (semanticCacheService == null) return false; var checksums = await document.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false); var checksum = checksums.Text; var result = await semanticCacheService.GetCachedSemanticClassificationsAsync( SemanticClassificationCacheUtilities.GetDocumentKeyForCaching(document), textSpan, checksum, cancellationToken).ConfigureAwait(false); if (result.IsDefault) return false; classifiedSpans.AddRange(result); return true; } } }
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./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() ' If the option has Not been set by the user, check if the option to enable imports on paste ' 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.ImportsOnPasteDefaultEnabled) 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() ' If the option has Not been set by the user, check if the option to enable imports on paste ' 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.ImportsOnPasteDefaultEnabled) 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
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/BKTree.Serialization.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 Microsoft.CodeAnalysis.Internal.Log; namespace Roslyn.Utilities { internal partial class BKTree { internal void WriteTo(ObjectWriter writer) { writer.WriteInt32(_concatenatedLowerCaseWords.Length); foreach (var c in _concatenatedLowerCaseWords) { writer.WriteChar(c); } writer.WriteInt32(_nodes.Length); foreach (var node in _nodes) { node.WriteTo(writer); } writer.WriteInt32(_edges.Length); foreach (var edge in _edges) { edge.WriteTo(writer); } } internal static BKTree? ReadFrom(ObjectReader reader) { try { var concatenatedLowerCaseWords = new char[reader.ReadInt32()]; for (var i = 0; i < concatenatedLowerCaseWords.Length; i++) { concatenatedLowerCaseWords[i] = reader.ReadChar(); } var nodeCount = reader.ReadInt32(); var nodes = ImmutableArray.CreateBuilder<Node>(nodeCount); for (var i = 0; i < nodeCount; i++) { nodes.Add(Node.ReadFrom(reader)); } var edgeCount = reader.ReadInt32(); var edges = ImmutableArray.CreateBuilder<Edge>(edgeCount); for (var i = 0; i < edgeCount; i++) { edges.Add(Edge.ReadFrom(reader)); } return new BKTree(concatenatedLowerCaseWords, nodes.MoveToImmutable(), edges.MoveToImmutable()); } catch { Logger.Log(FunctionId.BKTree_ExceptionInCacheRead); return null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.Internal.Log; namespace Roslyn.Utilities { internal partial class BKTree { internal void WriteTo(ObjectWriter writer) { writer.WriteInt32(_concatenatedLowerCaseWords.Length); foreach (var c in _concatenatedLowerCaseWords) { writer.WriteChar(c); } writer.WriteInt32(_nodes.Length); foreach (var node in _nodes) { node.WriteTo(writer); } writer.WriteInt32(_edges.Length); foreach (var edge in _edges) { edge.WriteTo(writer); } } internal static BKTree? ReadFrom(ObjectReader reader) { try { var concatenatedLowerCaseWords = new char[reader.ReadInt32()]; for (var i = 0; i < concatenatedLowerCaseWords.Length; i++) { concatenatedLowerCaseWords[i] = reader.ReadChar(); } var nodeCount = reader.ReadInt32(); var nodes = ImmutableArray.CreateBuilder<Node>(nodeCount); for (var i = 0; i < nodeCount; i++) { nodes.Add(Node.ReadFrom(reader)); } var edgeCount = reader.ReadInt32(); var edges = ImmutableArray.CreateBuilder<Edge>(edgeCount); for (var i = 0; i < edgeCount; i++) { edges.Add(Edge.ReadFrom(reader)); } return new BKTree(concatenatedLowerCaseWords, nodes.MoveToImmutable(), edges.MoveToImmutable()); } catch { Logger.Log(FunctionId.BKTree_ExceptionInCacheRead); return null; } } } }
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_RaiseEvent.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.Diagnostics Imports Microsoft.CodeAnalysis.RuntimeMembers Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitRaiseEventStatement(node As BoundRaiseEventStatement) As BoundNode Dim syntax = node.Syntax Dim saveState As UnstructuredExceptionHandlingContext = LeaveUnstructuredExceptionHandlingContext(node) ' in the absence of errors invocation must be a call '(could also be BadExpression, but that would have errors) Dim raiseCallExpression = DirectCast(node.EventInvocation, BoundCall) Dim result As BoundStatement Dim receiver = raiseCallExpression.ReceiverOpt If receiver Is Nothing OrElse receiver.IsMeReference Then result = New BoundExpressionStatement( syntax, VisitExpressionNode(raiseCallExpression)) Else Debug.Assert(receiver.Kind = BoundKind.FieldAccess) #If DEBUG Then ' NOTE: The receiver is always as lowered as it's going to get (generally, a MeReference), so there's no need to Visit it. Dim fieldAccess As BoundFieldAccess = DirectCast(receiver, BoundFieldAccess) Dim fieldAccessReceiver = fieldAccess.ReceiverOpt Debug.Assert(fieldAccessReceiver Is Nothing OrElse fieldAccessReceiver.Kind = BoundKind.MeReference) #End If If node.EventSymbol.IsWindowsRuntimeEvent Then receiver = GetWindowsRuntimeEventReceiver(syntax, receiver) End If ' Need to null-check the receiver before invoking raise - ' ' eventField.raiseCallExpression === becomes ===> ' ' Block ' Dim temp = eventField ' if temp is Nothing GoTo skipEventRaise ' Call temp.raiseCallExpression ' skipEventRaise: ' End Block ' Dim temp As LocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, receiver.Type, SynthesizedLocalKind.LoweringTemp) Dim tempAccess As BoundLocal = New BoundLocal(syntax, temp, temp.Type).MakeCompilerGenerated Dim tempInit = New BoundExpressionStatement(syntax, New BoundAssignmentOperator(syntax, tempAccess, receiver, True, receiver.Type)).MakeCompilerGenerated ' replace receiver with temp. raiseCallExpression = raiseCallExpression.Update(raiseCallExpression.Method, raiseCallExpression.MethodGroupOpt, tempAccess, raiseCallExpression.Arguments, raiseCallExpression.DefaultArguments, raiseCallExpression.ConstantValueOpt, isLValue:=raiseCallExpression.IsLValue, suppressObjectClone:=raiseCallExpression.SuppressObjectClone, type:=raiseCallExpression.Type) Dim invokeStatement = New BoundExpressionStatement( syntax, VisitExpressionNode(raiseCallExpression)) Dim condition = New BoundBinaryOperator(syntax, BinaryOperatorKind.Is, tempAccess.MakeRValue(), New BoundLiteral(syntax, ConstantValue.Nothing, Me.Compilation.GetSpecialType(SpecialType.System_Object)), False, Me.Compilation.GetSpecialType(SpecialType.System_Boolean)).MakeCompilerGenerated Dim skipEventRaise As New GeneratedLabelSymbol("skipEventRaise") Dim ifNullSkip = New BoundConditionalGoto(syntax, condition, True, skipEventRaise).MakeCompilerGenerated result = New BoundBlock(syntax, Nothing, ImmutableArray.Create(temp), ImmutableArray.Create(Of BoundStatement)( tempInit, ifNullSkip, invokeStatement, New BoundLabelStatement(syntax, skipEventRaise))) End If RestoreUnstructuredExceptionHandlingContext(node, saveState) If ShouldGenerateUnstructuredExceptionHandlingResumeCode(node) Then result = RegisterUnstructuredExceptionHandlingResumeTarget(node.Syntax, result, canThrow:=True) End If If Instrument(node, result) Then result = _instrumenterOpt.InstrumentRaiseEventStatement(node, result) End If Return result End Function ' If the event is a WinRT event, then the backing field is actually an EventRegistrationTokenTable, ' rather than a delegate. If this is the case, then we replace the receiver with ' EventRegistrationTokenTable(Of Event).GetOrCreateEventRegistrationTokenTable(eventField).InvocationList. Private Function GetWindowsRuntimeEventReceiver(syntax As SyntaxNode, rewrittenReceiver As BoundExpression) As BoundExpression Dim fieldType As NamedTypeSymbol = DirectCast(rewrittenReceiver.Type, NamedTypeSymbol) Debug.Assert(fieldType.Name = "EventRegistrationTokenTable") Dim getOrCreateMethod As MethodSymbol = DirectCast(Compilation.GetWellKnownTypeMember( WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__GetOrCreateEventRegistrationTokenTable), MethodSymbol) Debug.Assert(getOrCreateMethod IsNot Nothing, "Checked during initial binding") Debug.Assert(TypeSymbol.Equals(getOrCreateMethod.ReturnType, fieldType.OriginalDefinition, TypeCompareKind.ConsiderEverything), "Shape of well-known member") getOrCreateMethod = getOrCreateMethod.AsMember(fieldType) Dim invocationListProperty As PropertySymbol = Nothing If TryGetWellknownMember(invocationListProperty, WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__InvocationList, syntax) Then Dim invocationListAccessor As MethodSymbol = invocationListProperty.GetMethod If invocationListAccessor IsNot Nothing Then invocationListAccessor = invocationListAccessor.AsMember(fieldType) ' EventRegistrationTokenTable(Of Event).GetOrCreateEventRegistrationTokenTable(_tokenTable) Dim getOrCreateCall = New BoundCall(syntax:=syntax, method:=getOrCreateMethod, methodGroupOpt:=Nothing, receiverOpt:=Nothing, arguments:=ImmutableArray.Create(Of BoundExpression)(rewrittenReceiver), constantValueOpt:=Nothing, isLValue:=False, suppressObjectClone:=False, type:=getOrCreateMethod.ReturnType).MakeCompilerGenerated() ' EventRegistrationTokenTable(Of Event).GetOrCreateEventRegistrationTokenTable(_tokenTable).InvocationList Dim invocationListAccessorCall = New BoundCall(syntax:=syntax, method:=invocationListAccessor, methodGroupOpt:=Nothing, receiverOpt:=getOrCreateCall, arguments:=ImmutableArray(Of BoundExpression).Empty, constantValueOpt:=Nothing, isLValue:=False, suppressObjectClone:=False, type:=invocationListAccessor.ReturnType).MakeCompilerGenerated() Return invocationListAccessorCall End If Dim memberDescriptor As MemberDescriptor = WellKnownMembers.GetDescriptor(WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__InvocationList) ' isWinMd only matters for set accessors, we can safely say false here Dim accessorName As String = Binder.GetAccessorName(invocationListProperty.Name, MethodKind.PropertyGet, isWinMd:=False) Dim info = GetDiagnosticForMissingRuntimeHelper(memberDescriptor.DeclaringTypeMetadataName, accessorName, _compilationState.Compilation.Options.EmbedVbCoreRuntime) _diagnostics.Add(info, syntax.GetLocation()) End If Return New BoundBadExpression(syntax, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, ImmutableArray.Create(rewrittenReceiver), ErrorTypeSymbol.UnknownResultType, hasErrors:=True) 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.Diagnostics Imports Microsoft.CodeAnalysis.RuntimeMembers Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitRaiseEventStatement(node As BoundRaiseEventStatement) As BoundNode Dim syntax = node.Syntax Dim saveState As UnstructuredExceptionHandlingContext = LeaveUnstructuredExceptionHandlingContext(node) ' in the absence of errors invocation must be a call '(could also be BadExpression, but that would have errors) Dim raiseCallExpression = DirectCast(node.EventInvocation, BoundCall) Dim result As BoundStatement Dim receiver = raiseCallExpression.ReceiverOpt If receiver Is Nothing OrElse receiver.IsMeReference Then result = New BoundExpressionStatement( syntax, VisitExpressionNode(raiseCallExpression)) Else Debug.Assert(receiver.Kind = BoundKind.FieldAccess) #If DEBUG Then ' NOTE: The receiver is always as lowered as it's going to get (generally, a MeReference), so there's no need to Visit it. Dim fieldAccess As BoundFieldAccess = DirectCast(receiver, BoundFieldAccess) Dim fieldAccessReceiver = fieldAccess.ReceiverOpt Debug.Assert(fieldAccessReceiver Is Nothing OrElse fieldAccessReceiver.Kind = BoundKind.MeReference) #End If If node.EventSymbol.IsWindowsRuntimeEvent Then receiver = GetWindowsRuntimeEventReceiver(syntax, receiver) End If ' Need to null-check the receiver before invoking raise - ' ' eventField.raiseCallExpression === becomes ===> ' ' Block ' Dim temp = eventField ' if temp is Nothing GoTo skipEventRaise ' Call temp.raiseCallExpression ' skipEventRaise: ' End Block ' Dim temp As LocalSymbol = New SynthesizedLocal(Me._currentMethodOrLambda, receiver.Type, SynthesizedLocalKind.LoweringTemp) Dim tempAccess As BoundLocal = New BoundLocal(syntax, temp, temp.Type).MakeCompilerGenerated Dim tempInit = New BoundExpressionStatement(syntax, New BoundAssignmentOperator(syntax, tempAccess, receiver, True, receiver.Type)).MakeCompilerGenerated ' replace receiver with temp. raiseCallExpression = raiseCallExpression.Update(raiseCallExpression.Method, raiseCallExpression.MethodGroupOpt, tempAccess, raiseCallExpression.Arguments, raiseCallExpression.DefaultArguments, raiseCallExpression.ConstantValueOpt, isLValue:=raiseCallExpression.IsLValue, suppressObjectClone:=raiseCallExpression.SuppressObjectClone, type:=raiseCallExpression.Type) Dim invokeStatement = New BoundExpressionStatement( syntax, VisitExpressionNode(raiseCallExpression)) Dim condition = New BoundBinaryOperator(syntax, BinaryOperatorKind.Is, tempAccess.MakeRValue(), New BoundLiteral(syntax, ConstantValue.Nothing, Me.Compilation.GetSpecialType(SpecialType.System_Object)), False, Me.Compilation.GetSpecialType(SpecialType.System_Boolean)).MakeCompilerGenerated Dim skipEventRaise As New GeneratedLabelSymbol("skipEventRaise") Dim ifNullSkip = New BoundConditionalGoto(syntax, condition, True, skipEventRaise).MakeCompilerGenerated result = New BoundBlock(syntax, Nothing, ImmutableArray.Create(temp), ImmutableArray.Create(Of BoundStatement)( tempInit, ifNullSkip, invokeStatement, New BoundLabelStatement(syntax, skipEventRaise))) End If RestoreUnstructuredExceptionHandlingContext(node, saveState) If ShouldGenerateUnstructuredExceptionHandlingResumeCode(node) Then result = RegisterUnstructuredExceptionHandlingResumeTarget(node.Syntax, result, canThrow:=True) End If If Instrument(node, result) Then result = _instrumenterOpt.InstrumentRaiseEventStatement(node, result) End If Return result End Function ' If the event is a WinRT event, then the backing field is actually an EventRegistrationTokenTable, ' rather than a delegate. If this is the case, then we replace the receiver with ' EventRegistrationTokenTable(Of Event).GetOrCreateEventRegistrationTokenTable(eventField).InvocationList. Private Function GetWindowsRuntimeEventReceiver(syntax As SyntaxNode, rewrittenReceiver As BoundExpression) As BoundExpression Dim fieldType As NamedTypeSymbol = DirectCast(rewrittenReceiver.Type, NamedTypeSymbol) Debug.Assert(fieldType.Name = "EventRegistrationTokenTable") Dim getOrCreateMethod As MethodSymbol = DirectCast(Compilation.GetWellKnownTypeMember( WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__GetOrCreateEventRegistrationTokenTable), MethodSymbol) Debug.Assert(getOrCreateMethod IsNot Nothing, "Checked during initial binding") Debug.Assert(TypeSymbol.Equals(getOrCreateMethod.ReturnType, fieldType.OriginalDefinition, TypeCompareKind.ConsiderEverything), "Shape of well-known member") getOrCreateMethod = getOrCreateMethod.AsMember(fieldType) Dim invocationListProperty As PropertySymbol = Nothing If TryGetWellknownMember(invocationListProperty, WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__InvocationList, syntax) Then Dim invocationListAccessor As MethodSymbol = invocationListProperty.GetMethod If invocationListAccessor IsNot Nothing Then invocationListAccessor = invocationListAccessor.AsMember(fieldType) ' EventRegistrationTokenTable(Of Event).GetOrCreateEventRegistrationTokenTable(_tokenTable) Dim getOrCreateCall = New BoundCall(syntax:=syntax, method:=getOrCreateMethod, methodGroupOpt:=Nothing, receiverOpt:=Nothing, arguments:=ImmutableArray.Create(Of BoundExpression)(rewrittenReceiver), constantValueOpt:=Nothing, isLValue:=False, suppressObjectClone:=False, type:=getOrCreateMethod.ReturnType).MakeCompilerGenerated() ' EventRegistrationTokenTable(Of Event).GetOrCreateEventRegistrationTokenTable(_tokenTable).InvocationList Dim invocationListAccessorCall = New BoundCall(syntax:=syntax, method:=invocationListAccessor, methodGroupOpt:=Nothing, receiverOpt:=getOrCreateCall, arguments:=ImmutableArray(Of BoundExpression).Empty, constantValueOpt:=Nothing, isLValue:=False, suppressObjectClone:=False, type:=invocationListAccessor.ReturnType).MakeCompilerGenerated() Return invocationListAccessorCall End If Dim memberDescriptor As MemberDescriptor = WellKnownMembers.GetDescriptor(WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__InvocationList) ' isWinMd only matters for set accessors, we can safely say false here Dim accessorName As String = Binder.GetAccessorName(invocationListProperty.Name, MethodKind.PropertyGet, isWinMd:=False) Dim info = GetDiagnosticForMissingRuntimeHelper(memberDescriptor.DeclaringTypeMetadataName, accessorName, _compilationState.Compilation.Options.EmbedVbCoreRuntime) _diagnostics.Add(info, syntax.GetLocation()) End If Return New BoundBadExpression(syntax, LookupResultKind.NotReferencable, ImmutableArray(Of Symbol).Empty, ImmutableArray.Create(rewrittenReceiver), ErrorTypeSymbol.UnknownResultType, hasErrors:=True) End Function End Class End Namespace
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/Trivia/CSharpTriviaFormatter.DocumentationCommentExteriorCommentRewriter.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.Diagnostics; using Microsoft.CodeAnalysis.Formatting; namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal partial class CSharpTriviaFormatter { private class DocumentationCommentExteriorCommentRewriter : CSharpSyntaxRewriter { private readonly bool _forceIndentation; private readonly int _indentation; private readonly int _indentationDelta; private readonly AnalyzerConfigOptions _options; public DocumentationCommentExteriorCommentRewriter( bool forceIndentation, int indentation, int indentationDelta, AnalyzerConfigOptions options, bool visitStructuredTrivia = true) : base(visitIntoStructuredTrivia: visitStructuredTrivia) { _forceIndentation = forceIndentation; _indentation = indentation; _indentationDelta = indentationDelta; _options = options; } public override SyntaxTrivia VisitTrivia(SyntaxTrivia trivia) { if (trivia.Kind() == SyntaxKind.DocumentationCommentExteriorTrivia) { if (IsBeginningOrEndOfDocumentComment(trivia)) { return base.VisitTrivia(trivia); } else { var triviaText = trivia.ToFullString(); var newTriviaText = triviaText.AdjustIndentForXmlDocExteriorTrivia( _forceIndentation, _indentation, _indentationDelta, _options.GetOption(FormattingOptions2.UseTabs), _options.GetOption(FormattingOptions2.TabSize)); if (triviaText == newTriviaText) { return base.VisitTrivia(trivia); } var parsedNewTrivia = SyntaxFactory.DocumentationCommentExterior(newTriviaText); return parsedNewTrivia; } } return base.VisitTrivia(trivia); } private static bool IsBeginningOrEndOfDocumentComment(SyntaxTrivia trivia) { var currentParent = trivia.Token.Parent; while (currentParent != null) { if (currentParent.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia || currentParent.Kind() == SyntaxKind.MultiLineDocumentationCommentTrivia) { if (trivia.Span.End == currentParent.SpanStart || trivia.Span.End == currentParent.Span.End) { return true; } else { return false; } } currentParent = currentParent.Parent; } return false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting; namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal partial class CSharpTriviaFormatter { private class DocumentationCommentExteriorCommentRewriter : CSharpSyntaxRewriter { private readonly bool _forceIndentation; private readonly int _indentation; private readonly int _indentationDelta; private readonly AnalyzerConfigOptions _options; public DocumentationCommentExteriorCommentRewriter( bool forceIndentation, int indentation, int indentationDelta, AnalyzerConfigOptions options, bool visitStructuredTrivia = true) : base(visitIntoStructuredTrivia: visitStructuredTrivia) { _forceIndentation = forceIndentation; _indentation = indentation; _indentationDelta = indentationDelta; _options = options; } public override SyntaxTrivia VisitTrivia(SyntaxTrivia trivia) { if (trivia.Kind() == SyntaxKind.DocumentationCommentExteriorTrivia) { if (IsBeginningOrEndOfDocumentComment(trivia)) { return base.VisitTrivia(trivia); } else { var triviaText = trivia.ToFullString(); var newTriviaText = triviaText.AdjustIndentForXmlDocExteriorTrivia( _forceIndentation, _indentation, _indentationDelta, _options.GetOption(FormattingOptions2.UseTabs), _options.GetOption(FormattingOptions2.TabSize)); if (triviaText == newTriviaText) { return base.VisitTrivia(trivia); } var parsedNewTrivia = SyntaxFactory.DocumentationCommentExterior(newTriviaText); return parsedNewTrivia; } } return base.VisitTrivia(trivia); } private static bool IsBeginningOrEndOfDocumentComment(SyntaxTrivia trivia) { var currentParent = trivia.Token.Parent; while (currentParent != null) { if (currentParent.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia || currentParent.Kind() == SyntaxKind.MultiLineDocumentationCommentTrivia) { if (trivia.Span.End == currentParent.SpanStart || trivia.Span.End == currentParent.Span.End) { return true; } else { return false; } } currentParent = currentParent.Parent; } return false; } } } }
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Binder/LookupOptions.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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Options that can be used to modify the symbol lookup mechanism. /// </summary> /// <remarks> /// Multiple options can be combined together. LookupOptions.AreValid checks for valid combinations. /// </remarks> [Flags] internal enum LookupOptions { /// <summary> /// Consider all symbols, using normal accessibility rules. /// </summary> Default = 0, /// <summary> /// Consider only namespace aliases and extern aliases. /// </summary> NamespaceAliasesOnly = 1 << 1, /// <summary> /// Consider only namespaces and types. /// </summary> NamespacesOrTypesOnly = 1 << 2, /// <summary> /// Consider non-members, plus invocable members. /// </summary> MustBeInvocableIfMember = 1 << 3, /// <summary> /// Consider only symbols that are instance members. Valid with IncludeExtensionMethods /// since extension methods are invoked on an instance. /// </summary> MustBeInstance = 1 << 4, /// <summary> /// Do not consider symbols that are instance members. /// </summary> MustNotBeInstance = 1 << 5, /// <summary> /// Do not consider symbols that are namespaces. /// </summary> MustNotBeNamespace = 1 << 6, /// <summary> /// Consider methods of any arity when arity zero is specified. Because type parameters can be inferred, it is /// often desired to consider generic methods when no type arguments were present. /// </summary> AllMethodsOnArityZero = 1 << 7, /// <summary> /// Look only for label symbols. This must be exclusive of all other options. /// </summary> LabelsOnly = 1 << 8, /// <summary> /// Usually, when determining if a member is accessible, both the type of the receiver /// and the type containing the access are used. If this flag is specified, then only /// the containing type will be used (i.e. as if you've written base.XX). /// </summary> UseBaseReferenceAccessibility = 1 << 9, /// <summary> /// Include extension methods. /// </summary> IncludeExtensionMethods = 1 << 10, /// <summary> /// Consider only attribute types. /// </summary> AttributeTypeOnly = (1 << 11) | NamespacesOrTypesOnly, /// <summary> /// Consider lookup name to be a verbatim identifier. /// If this flag is specified, then only one lookup is performed for attribute name: lookup with the given name, /// and attribute name lookup with "Attribute" suffix is skipped. /// </summary> VerbatimNameAttributeTypeOnly = (1 << 12) | AttributeTypeOnly, /// <summary> /// Consider named types of any arity when arity zero is specified. It is specifically desired for nameof in such situations: nameof(System.Collections.Generic.List) /// </summary> AllNamedTypesOnArityZero = 1 << 13, /// <summary> /// Do not consider symbols that are method type parameters. /// </summary> MustNotBeMethodTypeParameter = 1 << 14, /// <summary> /// Consider only symbols that are abstract. /// </summary> MustBeAbstract = 1 << 15, } internal static class LookupOptionExtensions { /// <summary> /// Are these options valid in their current combination? /// </summary> /// <remarks> /// Some checks made here: /// /// - Default is valid. /// - If LabelsOnly is set, it must be the only option. /// - If one of MustBeInstance or MustNotBeInstance are set, the other one must not be set. /// - If any of MustNotBeInstance, MustBeInstance, or MustNotBeNonInvocableMember are set, /// the options are considered valid. /// - If MustNotBeNamespace is set, neither NamespaceAliasesOnly nor NamespacesOrTypesOnly must be set. /// - Otherwise, only one of NamespaceAliasesOnly, NamespacesOrTypesOnly, or AllMethodsOnArityZero must be set. /// </remarks> internal static bool AreValid(this LookupOptions options) { if (options == LookupOptions.Default) { return true; } if ((options & LookupOptions.LabelsOnly) != 0) { return options == LookupOptions.LabelsOnly; } // These are exclusive; both must not be present. LookupOptions mustBeAndNotBeInstance = (LookupOptions.MustBeInstance | LookupOptions.MustNotBeInstance); if ((options & mustBeAndNotBeInstance) == mustBeAndNotBeInstance) { return false; } // If MustNotBeNamespace or MustNotBeMethodTypeParameter is set, neither NamespaceAliasesOnly nor NamespacesOrTypesOnly must be set. if ((options & (LookupOptions.MustNotBeNamespace | LookupOptions.MustNotBeMethodTypeParameter)) != 0 && (options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.NamespacesOrTypesOnly)) != 0) { return false; } LookupOptions onlyOptions = options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.NamespacesOrTypesOnly | LookupOptions.AllMethodsOnArityZero); return OnlyOneBitSet(onlyOptions); } internal static void ThrowIfInvalid(this LookupOptions options) { if (!options.AreValid()) { throw new ArgumentException(CSharpResources.LookupOptionsHasInvalidCombo); } } private static bool OnlyOneBitSet(LookupOptions o) { return (o & (o - 1)) == 0; } internal static bool CanConsiderMembers(this LookupOptions options) { return (options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.NamespacesOrTypesOnly | LookupOptions.LabelsOnly)) == 0; } internal static bool CanConsiderLocals(this LookupOptions options) { return (options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.NamespacesOrTypesOnly | LookupOptions.LabelsOnly)) == 0; } internal static bool CanConsiderTypes(this LookupOptions options) { return (options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.MustBeInvocableIfMember | LookupOptions.MustBeInstance | LookupOptions.LabelsOnly)) == 0; } internal static bool CanConsiderNamespaces(this LookupOptions options) { return (options & (LookupOptions.MustNotBeNamespace | LookupOptions.MustBeInvocableIfMember | LookupOptions.MustBeInstance | LookupOptions.LabelsOnly)) == 0; } internal static bool IsAttributeTypeLookup(this LookupOptions options) { return (options & LookupOptions.AttributeTypeOnly) == LookupOptions.AttributeTypeOnly; } internal static bool IsVerbatimNameAttributeTypeLookup(this LookupOptions options) { return (options & LookupOptions.VerbatimNameAttributeTypeOnly) == LookupOptions.VerbatimNameAttributeTypeOnly; } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Options that can be used to modify the symbol lookup mechanism. /// </summary> /// <remarks> /// Multiple options can be combined together. LookupOptions.AreValid checks for valid combinations. /// </remarks> [Flags] internal enum LookupOptions { /// <summary> /// Consider all symbols, using normal accessibility rules. /// </summary> Default = 0, /// <summary> /// Consider only namespace aliases and extern aliases. /// </summary> NamespaceAliasesOnly = 1 << 1, /// <summary> /// Consider only namespaces and types. /// </summary> NamespacesOrTypesOnly = 1 << 2, /// <summary> /// Consider non-members, plus invocable members. /// </summary> MustBeInvocableIfMember = 1 << 3, /// <summary> /// Consider only symbols that are instance members. Valid with IncludeExtensionMethods /// since extension methods are invoked on an instance. /// </summary> MustBeInstance = 1 << 4, /// <summary> /// Do not consider symbols that are instance members. /// </summary> MustNotBeInstance = 1 << 5, /// <summary> /// Do not consider symbols that are namespaces. /// </summary> MustNotBeNamespace = 1 << 6, /// <summary> /// Consider methods of any arity when arity zero is specified. Because type parameters can be inferred, it is /// often desired to consider generic methods when no type arguments were present. /// </summary> AllMethodsOnArityZero = 1 << 7, /// <summary> /// Look only for label symbols. This must be exclusive of all other options. /// </summary> LabelsOnly = 1 << 8, /// <summary> /// Usually, when determining if a member is accessible, both the type of the receiver /// and the type containing the access are used. If this flag is specified, then only /// the containing type will be used (i.e. as if you've written base.XX). /// </summary> UseBaseReferenceAccessibility = 1 << 9, /// <summary> /// Include extension methods. /// </summary> IncludeExtensionMethods = 1 << 10, /// <summary> /// Consider only attribute types. /// </summary> AttributeTypeOnly = (1 << 11) | NamespacesOrTypesOnly, /// <summary> /// Consider lookup name to be a verbatim identifier. /// If this flag is specified, then only one lookup is performed for attribute name: lookup with the given name, /// and attribute name lookup with "Attribute" suffix is skipped. /// </summary> VerbatimNameAttributeTypeOnly = (1 << 12) | AttributeTypeOnly, /// <summary> /// Consider named types of any arity when arity zero is specified. It is specifically desired for nameof in such situations: nameof(System.Collections.Generic.List) /// </summary> AllNamedTypesOnArityZero = 1 << 13, /// <summary> /// Do not consider symbols that are method type parameters. /// </summary> MustNotBeMethodTypeParameter = 1 << 14, /// <summary> /// Consider only symbols that are abstract. /// </summary> MustBeAbstract = 1 << 15, } internal static class LookupOptionExtensions { /// <summary> /// Are these options valid in their current combination? /// </summary> /// <remarks> /// Some checks made here: /// /// - Default is valid. /// - If LabelsOnly is set, it must be the only option. /// - If one of MustBeInstance or MustNotBeInstance are set, the other one must not be set. /// - If any of MustNotBeInstance, MustBeInstance, or MustNotBeNonInvocableMember are set, /// the options are considered valid. /// - If MustNotBeNamespace is set, neither NamespaceAliasesOnly nor NamespacesOrTypesOnly must be set. /// - Otherwise, only one of NamespaceAliasesOnly, NamespacesOrTypesOnly, or AllMethodsOnArityZero must be set. /// </remarks> internal static bool AreValid(this LookupOptions options) { if (options == LookupOptions.Default) { return true; } if ((options & LookupOptions.LabelsOnly) != 0) { return options == LookupOptions.LabelsOnly; } // These are exclusive; both must not be present. LookupOptions mustBeAndNotBeInstance = (LookupOptions.MustBeInstance | LookupOptions.MustNotBeInstance); if ((options & mustBeAndNotBeInstance) == mustBeAndNotBeInstance) { return false; } // If MustNotBeNamespace or MustNotBeMethodTypeParameter is set, neither NamespaceAliasesOnly nor NamespacesOrTypesOnly must be set. if ((options & (LookupOptions.MustNotBeNamespace | LookupOptions.MustNotBeMethodTypeParameter)) != 0 && (options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.NamespacesOrTypesOnly)) != 0) { return false; } LookupOptions onlyOptions = options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.NamespacesOrTypesOnly | LookupOptions.AllMethodsOnArityZero); return OnlyOneBitSet(onlyOptions); } internal static void ThrowIfInvalid(this LookupOptions options) { if (!options.AreValid()) { throw new ArgumentException(CSharpResources.LookupOptionsHasInvalidCombo); } } private static bool OnlyOneBitSet(LookupOptions o) { return (o & (o - 1)) == 0; } internal static bool CanConsiderMembers(this LookupOptions options) { return (options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.NamespacesOrTypesOnly | LookupOptions.LabelsOnly)) == 0; } internal static bool CanConsiderLocals(this LookupOptions options) { return (options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.NamespacesOrTypesOnly | LookupOptions.LabelsOnly)) == 0; } internal static bool CanConsiderTypes(this LookupOptions options) { return (options & (LookupOptions.NamespaceAliasesOnly | LookupOptions.MustBeInvocableIfMember | LookupOptions.MustBeInstance | LookupOptions.LabelsOnly)) == 0; } internal static bool CanConsiderNamespaces(this LookupOptions options) { return (options & (LookupOptions.MustNotBeNamespace | LookupOptions.MustBeInvocableIfMember | LookupOptions.MustBeInstance | LookupOptions.LabelsOnly)) == 0; } internal static bool IsAttributeTypeLookup(this LookupOptions options) { return (options & LookupOptions.AttributeTypeOnly) == LookupOptions.AttributeTypeOnly; } internal static bool IsVerbatimNameAttributeTypeLookup(this LookupOptions options) { return (options & LookupOptions.VerbatimNameAttributeTypeOnly) == LookupOptions.VerbatimNameAttributeTypeOnly; } } }
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Test/Semantic/Semantics/NameLengthTests.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.IO; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Microsoft.Cci; using System; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class NameLengthTests : CSharpTestBase { // Longest legal symbol name. private static readonly string s_longSymbolName = new string('A', MetadataWriter.NameLengthLimit); // Longest legal path name. private static readonly string s_longPathName = new string('A', MetadataWriter.PathLengthLimit); // Longest legal local name. private static readonly string s_longLocalName = new string('A', MetadataWriter.PdbLengthLimit); [Fact] public void UnmangledMemberNames() { var sourceTemplate = @" using System; class Fields {{ int {0}; // Fine int {0}1; // Too long }} class FieldLikeEvents {{ event Action {0}; // Fine (except accessors) event Action {0}1; // Too long }} class CustomEvents {{ event Action {0} {{ add {{ }} remove {{ }} }} // Fine (except accessors) event Action {0}1 {{ add {{ }} remove {{ }} }} // Too long }} class AutoProperties {{ int {0} {{ get; set; }} // Fine (except accessors and backing field) int {0}1 {{ get; set; }} // Too long }} class CustomProperties {{ int {0} {{ get {{ return 0; }} set {{ }} }} // Fine (except accessors) int {0}1 {{ get {{ return 0; }} set {{ }} }} // Too long }} class Methods {{ void {0}() {{ }} // Fine void {0}1() {{ }} // Too long }} "; var source = string.Format(sourceTemplate, s_longSymbolName); var comp = CreateCompilation(source); comp.VerifyDiagnostics( // Uninteresting // (6,9): warning CS0169: The field 'Fields.LongSymbolName' is never used // int LongSymbolName; // Fine Diagnostic(ErrorCode.WRN_UnreferencedField, s_longSymbolName).WithArguments("Fields." + s_longSymbolName).WithLocation(6, 9), // (7,9): warning CS0169: The field 'Fields.LongSymbolName + 1' is never used // int LongSymbolName + 1; // Too long Diagnostic(ErrorCode.WRN_UnreferencedField, s_longSymbolName + 1).WithArguments("Fields." + s_longSymbolName + 1).WithLocation(7, 9), // (12,18): warning CS0067: The event 'FieldLikeEvents.LongSymbolName' is never used // event Action LongSymbolName; // Fine Diagnostic(ErrorCode.WRN_UnreferencedEvent, s_longSymbolName).WithArguments("FieldLikeEvents." + s_longSymbolName).WithLocation(12, 18), // (13,18): warning CS0067: The event 'FieldLikeEvents.LongSymbolName + 1' is never used // event Action LongSymbolName + 1; // Too long Diagnostic(ErrorCode.WRN_UnreferencedEvent, s_longSymbolName + 1).WithArguments("FieldLikeEvents." + s_longSymbolName + 1).WithLocation(13, 18)); comp.VerifyEmitDiagnostics( // (7,9): error CS7013: Name 'LongSymbolName + 1' exceeds the maximum length allowed in metadata. // int LongSymbolName + 1; // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(7, 9), // (12,18): error CS7013: Name 'add_LongSymbolName' exceeds the maximum length allowed in metadata. // event Action LongSymbolName; // Fine (except accessors) Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName).WithArguments("add_" + s_longSymbolName).WithLocation(12, 18), // (12,18): error CS7013: Name 'remove_LongSymbolName' exceeds the maximum length allowed in metadata. // event Action LongSymbolName; // Fine (except accessors) Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName).WithArguments("remove_" + s_longSymbolName).WithLocation(12, 18), // (13,18): error CS7013: Name 'LongSymbolName + 1' exceeds the maximum length allowed in metadata. // event Action LongSymbolName + 1; // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(13, 18), // (13,18): error CS7013: Name 'LongSymbolName + 1' exceeds the maximum length allowed in metadata. // event Action LongSymbolName + 1; // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(13, 18), // Would be nice not to report on the backing field. // (13,18): error CS7013: Name 'add_LongSymbolName + 1' exceeds the maximum length allowed in metadata. // event Action LongSymbolName + 1; // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments("add_" + s_longSymbolName + 1).WithLocation(13, 18), // (13,18): error CS7013: Name 'remove_LongSymbolName + 1' exceeds the maximum length allowed in metadata. // event Action LongSymbolName + 1; // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments("remove_" + s_longSymbolName + 1).WithLocation(13, 18), // (18,1044): error CS7013: Name 'add_LongSymbolName' exceeds the maximum length allowed in metadata. // event Action LongSymbolName { add { } remove { } } // Fine (except accessors) Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "add").WithArguments("add_" + s_longSymbolName).WithLocation(18, 1044), // (18,1052): error CS7013: Name 'remove_LongSymbolName' exceeds the maximum length allowed in metadata. // event Action LongSymbolName { add { } remove { } } // Fine (except accessors) Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "remove").WithArguments("remove_" + s_longSymbolName).WithLocation(18, 1052), // (19,18): error CS7013: Name 'LongSymbolName + 1' exceeds the maximum length allowed in metadata. // event Action LongSymbolName + 1 { add { } remove { } } // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(19, 18), // (19,1045): error CS7013: Name 'add_LongSymbolName + 1' exceeds the maximum length allowed in metadata. // event Action LongSymbolName + 1 { add { } remove { } } // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "add").WithArguments("add_" + s_longSymbolName + 1).WithLocation(19, 1045), // (19,1053): error CS7013: Name 'remove_LongSymbolName + 1' exceeds the maximum length allowed in metadata. // event Action LongSymbolName + 1 { add { } remove { } } // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "remove").WithArguments("remove_" + s_longSymbolName + 1).WithLocation(19, 1053), // (24,9): error CS7013: Name '<LongSymbolName>k__BackingField' exceeds the maximum length allowed in metadata. // int LongSymbolName { get; set; } // Fine (except accessors and backing field) Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName).WithArguments("<" + s_longSymbolName + ">k__BackingField").WithLocation(24, 9), // (24,1035): error CS7013: Name 'get_LongSymbolName' exceeds the maximum length allowed in metadata. // int LongSymbolName { get; set; } // Fine (except accessors and backing field) Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "get").WithArguments("get_" + s_longSymbolName).WithLocation(24, 1035), // (24,1040): error CS7013: Name 'set_LongSymbolName' exceeds the maximum length allowed in metadata. // int LongSymbolName { get; set; } // Fine (except accessors and backing field) Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "set").WithArguments("set_" + s_longSymbolName).WithLocation(24, 1040), // (25,9): error CS7013: Name 'LongSymbolName + 1' exceeds the maximum length allowed in metadata. // int LongSymbolName + 1 { get; set; } // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(25, 9), // (25,9): error CS7013: Name '<LongSymbolName + 1>k__BackingField' exceeds the maximum length allowed in metadata. // int LongSymbolName + 1 { get; set; } // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments("<" + s_longSymbolName + "1>k__BackingField").WithLocation(25, 9), // (25,1036): error CS7013: Name 'get_LongSymbolName + 1' exceeds the maximum length allowed in metadata. // int LongSymbolName + 1 { get; set; } // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "get").WithArguments("get_" + s_longSymbolName + 1).WithLocation(25, 1036), // (25,1041): error CS7013: Name 'set_LongSymbolName + 1' exceeds the maximum length allowed in metadata. // int LongSymbolName + 1 { get; set; } // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "set").WithArguments("set_" + s_longSymbolName + 1).WithLocation(25, 1041), // (30,1035): error CS7013: Name 'get_LongSymbolName' exceeds the maximum length allowed in metadata. // int LongSymbolName { get { return 0; } set { } } // Fine (except accessors) Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "get").WithArguments("get_" + s_longSymbolName).WithLocation(30, 1035), // (30,1053): error CS7013: Name 'set_LongSymbolName' exceeds the maximum length allowed in metadata. // int LongSymbolName { get { return 0; } set { } } // Fine (except accessors) Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "set").WithArguments("set_" + s_longSymbolName).WithLocation(30, 1053), // (31,9): error CS7013: Name 'LongSymbolName + 1' exceeds the maximum length allowed in metadata. // int LongSymbolName + 1 { get { return 0; } set { } } // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(31, 9), // (31,1036): error CS7013: Name 'get_LongSymbolName + 1' exceeds the maximum length allowed in metadata. // int LongSymbolName + 1 { get { return 0; } set { } } // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "get").WithArguments("get_" + s_longSymbolName + 1).WithLocation(31, 1036), // (31,1054): error CS7013: Name 'set_LongSymbolName + 1' exceeds the maximum length allowed in metadata. // int LongSymbolName + 1 { get { return 0; } set { } } // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "set").WithArguments("set_" + s_longSymbolName + 1).WithLocation(31, 1054), // (37,10): error CS7013: Name 'LongSymbolName + 1' exceeds the maximum length allowed in metadata. // void LongSymbolName + 1() { } // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(37, 10), // Uninteresting // (6,9): warning CS0169: The field 'Fields.LongSymbolName' is never used // int LongSymbolName; // Fine Diagnostic(ErrorCode.WRN_UnreferencedField, s_longSymbolName).WithArguments("Fields." + s_longSymbolName).WithLocation(6, 9), // (7,9): warning CS0169: The field 'Fields.LongSymbolName + 1' is never used // int LongSymbolName + 1; // Too long Diagnostic(ErrorCode.WRN_UnreferencedField, s_longSymbolName + 1).WithArguments("Fields." + s_longSymbolName + 1).WithLocation(7, 9), // (12,18): warning CS0067: The event 'FieldLikeEvents.LongSymbolName' is never used // event Action LongSymbolName; // Fine Diagnostic(ErrorCode.WRN_UnreferencedEvent, s_longSymbolName).WithArguments("FieldLikeEvents." + s_longSymbolName).WithLocation(12, 18), // (13,18): warning CS0067: The event 'FieldLikeEvents.LongSymbolName + 1' is never used // event Action LongSymbolName + 1; // Too long Diagnostic(ErrorCode.WRN_UnreferencedEvent, s_longSymbolName + 1).WithArguments("FieldLikeEvents." + s_longSymbolName + 1).WithLocation(13, 18)); } [Fact] public void EmptyNamespaces() { var sourceTemplate = @" namespace {0} {{ }} // Fine. namespace {0}1 {{ }} // Too long, but not checked. "; var source = string.Format(sourceTemplate, s_longSymbolName); var comp = CreateCompilation(source); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics(); } [Fact] public void NonGeneratedTypeNames() { // {n} == LongSymbolName.Substring(n) var sourceTemplate = @" class {0} {{ }} // Fine class {0}1 {{ }} // Too long namespace N {{ struct {2} {{ }} // Fine struct {2}1 {{ }} // Too long after prepending 'N.' }} class Outer {{ enum {0} {{ }} // Fine, since outer class is not prepended enum {0}1 {{ }} // Too long }} interface {2}<T> {{ }} // Fine interface {2}1<T> {{ }} // Too long after appending '`1' "; var substring0 = s_longSymbolName; var substring1 = s_longSymbolName.Substring(1); var substring2 = s_longSymbolName.Substring(2); var source = string.Format(sourceTemplate, substring0, substring1, substring2); var comp = CreateCompilation(source); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( // (3,7): // class Diagnostic(ErrorCode.ERR_MetadataNameTooLong, substring0 + 1).WithArguments(substring0 + 1).WithLocation(3, 7), // (8,12): // struct Diagnostic(ErrorCode.ERR_MetadataNameTooLong, substring2 + 1).WithArguments("N." + substring2 + 1).WithLocation(8, 12), // (14,10): // enum Diagnostic(ErrorCode.ERR_MetadataNameTooLong, substring0 + 1).WithArguments(substring0 + 1).WithLocation(14, 10), // (18,11): // interface Diagnostic(ErrorCode.ERR_MetadataNameTooLong, substring2 + 1).WithArguments(substring2 + "1`1").WithLocation(18, 11)); } [Fact] public void ExplicitInterfaceImplementation() { var sourceTemplate = @" interface I {{ void {0}(); void {0}1(); }} namespace N {{ interface J<T> {{ void {1}(); void {1}1(); }} }} class C : I, N.J<C> {{ void I.{0}() {{ }} void I.{0}1() {{ }} void N.J<C>.{1}() {{ }} void N.J<C>.{1}1() {{ }} }} "; var name0 = s_longSymbolName.Substring(2); // Space for "I." var name1 = s_longSymbolName.Substring(7); // Space for "N.J<C>." var source = string.Format(sourceTemplate, name0, name1); var comp = CreateCompilation(source); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( // (20,12): // void I.{0}1() { } Diagnostic(ErrorCode.ERR_MetadataNameTooLong, name0 + 1).WithArguments("I." + name0 + 1).WithLocation(20, 12), // (23,17): // void N.J<C>.{1}1() { } Diagnostic(ErrorCode.ERR_MetadataNameTooLong, name1 + 1).WithArguments("N.J<C>." + name1 + 1).WithLocation(23, 17)); } [Fact] public void DllImport() { var sourceTemplate = @" using System.Runtime.InteropServices; class C1 {{ [DllImport(""goo.dll"", EntryPoint = ""Short1"")] static extern void {0}(); // Name is fine, entrypoint is fine. [DllImport(""goo.dll"", EntryPoint = ""Short2"")] static extern void {0}1(); // Name is too long, entrypoint is fine. }} class C2 {{ [DllImport(""goo.dll"", EntryPoint = ""{0}"")] static extern void Short1(); // Name is fine, entrypoint is fine. [DllImport(""goo.dll"", EntryPoint = ""{0}1"")] static extern void Short2(); // Name is fine, entrypoint is too long. }} class C3 {{ [DllImport(""goo.dll"")] static extern void {0}(); // Name is fine, entrypoint is unspecified. [DllImport(""goo.dll"")] static extern void {0}1(); // Name is too long, entrypoint is unspecified. }} "; var source = string.Format(sourceTemplate, s_longSymbolName); var comp = CreateCompilation(source); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( // (9,24): Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(9, 24), // (17,24): Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "Short2").WithArguments(s_longSymbolName + 1).WithLocation(17, 24), // (25,24): Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(25, 24)); } [Fact] public void Parameters() { var sourceTemplate = @" class C {{ void M(bool {0}) {{ }} void M(long {0}1) {{ }} int this[bool {0}] {{ get {{ return 0; }} }} int this[long {0}1] {{ get {{ return 0; }} }} delegate void D1(bool {0}); delegate void D2(long {0}1); }} "; var source = string.Format(sourceTemplate, s_longSymbolName); var comp = CreateCompilation(source); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( // (5,17): error CS7013: Name 'LongSymbolName + 1' exceeds the maximum length allowed in metadata. // void M(long LongSymbolName + 1) { } Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(5, 17), // (7,19): error CS7013: Name 'LongSymbolName + 1' exceeds the maximum length allowed in metadata. // int this[long LongSymbolName + 1] { get { return 0; } } Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(7, 19), // (9,27): error CS7013: Name 'LongSymbolName + 1' exceeds the maximum length allowed in metadata. // delegate void D2(long LongSymbolName + 1); Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(9, 27), // (9,27): error CS7013: Name 'LongSymbolName + 1' exceeds the maximum length allowed in metadata. // delegate void D2(long LongSymbolName + 1); Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(9, 27)); // Second report is for Invoke method. Not ideal, but not urgent. } [Fact] public void TypeParameters() { var sourceTemplate = @" class C<{0}, {0}1> {{ }} delegate void D<{0}, {0}1>(); class E {{ void M<{0}, {0}1>() {{ }} }} "; var source = string.Format(sourceTemplate, s_longSymbolName); var comp = CreateCompilation(source); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( // (2,1034): error CS7013: Name 'LongSymbolName + 1' exceeds the maximum length allowed in metadata. // class C<LongSymbolName, LongSymbolName + 1> Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(2, 1034), // (6,1042): error CS7013: Name 'LongSymbolName + 1' exceeds the maximum length allowed in metadata. // delegate void D<LongSymbolName, LongSymbolName + 1>(); Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(6, 1042), // (10,1037): error CS7013: Name 'LongSymbolName + 1' exceeds the maximum length allowed in metadata. // void M<LongSymbolName, LongSymbolName + 1>() { } Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(10, 1037)); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void Locals() { var sourceTemplate = @" class C {{ int M() {{ int {0} = 1; int {0}1 = 1; return {0} + {0}1; }} }} "; var source = string.Format(sourceTemplate, s_longLocalName); var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( options: TestOptions.NativePdbEmit, // (7,13): warning CS8029: Local name 'LongLocalName + 1' is too long for PDB. Consider shortening or compiling without /debug. // int LongSymbolName + 1 = 1; Diagnostic(ErrorCode.WRN_PdbLocalNameTooLong, s_longLocalName + 1).WithArguments(s_longLocalName + 1).WithLocation(7, 13)); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void ConstantLocals() { var sourceTemplate = @" class C {{ int M() {{ const int {0} = 1; const int {0}1 = 1; return {0} + {0}1; }} }} "; var source = string.Format(sourceTemplate, s_longLocalName); var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( options: TestOptions.NativePdbEmit, // (7,19): warning CS8029: Local name 'LongSymbolName + 1' is too long for PDB. Consider shortening or compiling without /debug. // const int LongSymbolName + 1 = 1; Diagnostic(ErrorCode.WRN_PdbLocalNameTooLong, s_longLocalName + 1).WithArguments(s_longLocalName + 1).WithLocation(7, 19)); } [Fact] public void TestLambdaMethods() { var sourceTemplate = @" using System; class C {{ Func<int> {0}(int p) {{ return () => p - 1; }} Func<int> {0}1(int p) {{ return () => p + 1; }} }} "; int padding = GeneratedNames.MakeLambdaMethodName("A", -1, 0, 0, 0).Length - 1; string longName = s_longSymbolName.Substring(padding); var source = string.Format(sourceTemplate, longName); var comp = CreateCompilation(source); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( // (13,16): error CS7013: Name '<longName + 1>b__3' exceeds the maximum length allowed in metadata. // return () => p + 1; Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "() => p + 1").WithArguments("<" + longName + "1>b__0").WithLocation(13, 16)); } [Fact] public void TestAnonymousTypeProperties() { var sourceTemplate = @" class C {{ object M() {{ return new {{ {0} = 1, {0}1 = 'a' }}; }} }} "; int padding = GeneratedNames.MakeAnonymousTypeBackingFieldName("A").Length - 1; string longName = s_longSymbolName.Substring(padding); var source = string.Format(sourceTemplate, longName); var comp = CreateCompilation(source); comp.VerifyDiagnostics(); // CONSIDER: Double reporting (once for field def, once for member ref) is not ideal. // CONSIDER: No location since the synthesized field symbol doesn't have one (would light up automatically). comp.VerifyEmitDiagnostics( // error CS7013: Name '<longName1>i__Field' exceeds the maximum length allowed in metadata. Diagnostic(ErrorCode.ERR_MetadataNameTooLong).WithArguments("<" + longName + 1 + ">i__Field").WithLocation(1, 1), // error CS7013: Name '<longName1>i__Field' exceeds the maximum length allowed in metadata. Diagnostic(ErrorCode.ERR_MetadataNameTooLong).WithArguments("<" + longName + 1 + ">i__Field").WithLocation(1, 1)); } [Fact] public void TestStateMachineMethods() { var sourceTemplate = @" using System.Collections.Generic; using System.Threading.Tasks; class Iterators {{ IEnumerable<int> {0}() {{ yield return 1; }} IEnumerable<int> {0}1() {{ yield return 1; }} }} class Async {{ async Task {0}() {{ await {0}(); }} async Task {0}1() {{ await {0}1(); }} }} "; int padding = GeneratedNames.MakeStateMachineTypeName("A", 0, 0).Length - 1; string longName = s_longSymbolName.Substring(padding); var source = string.Format(sourceTemplate, longName); var comp = CreateCompilationWithMscorlib45(source); comp.VerifyDiagnostics(); // CONSIDER: Location would light up if synthesized methods had them. comp.VerifyEmitDiagnostics( // error CS7013: Name '<longName1>d__1' exceeds the maximum length allowed in metadata. Diagnostic(ErrorCode.ERR_MetadataNameTooLong).WithArguments("<" + longName + 1 + ">d__1").WithLocation(1, 1), // error CS7013: Name '<longName1>d__1' exceeds the maximum length allowed in metadata. Diagnostic(ErrorCode.ERR_MetadataNameTooLong).WithArguments("<" + longName + 1 + ">d__1").WithLocation(1, 1)); } [WorkItem(531484, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531484")] [Fact] public void TestFixedSizeBuffers() { var sourceTemplate = @" unsafe struct S {{ fixed int {0}[1]; fixed int {0}1[1]; }} "; int padding = GeneratedNames.MakeFixedFieldImplementationName("A").Length - 1; string longName = s_longSymbolName.Substring(padding); var source = string.Format(sourceTemplate, longName); var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics(); // CONSIDER: Location would light up if synthesized methods had them. comp.VerifyEmitDiagnostics( // error CS7013: Name '<longName1>e__FixedBuffer' exceeds the maximum length allowed in metadata. Diagnostic(ErrorCode.ERR_MetadataNameTooLong).WithArguments("<" + longName + 1 + ">e__FixedBuffer").WithLocation(1, 1)); } [Fact] public void TestResources() { var source = "class C { }"; var comp = CreateCompilation(source); Func<Stream> dataProvider = () => new System.IO.MemoryStream(); var resources = new[] { new ResourceDescription("name1", "path1", dataProvider, false), //fine new ResourceDescription(s_longSymbolName, "path2", dataProvider, false), //fine new ResourceDescription("name2", s_longPathName, dataProvider, false), //fine new ResourceDescription(s_longSymbolName + 1, "path3", dataProvider, false), //name error new ResourceDescription("name3", s_longPathName + 2, dataProvider, false), //path error new ResourceDescription(s_longSymbolName + 3, s_longPathName + 4, dataProvider, false), //name and path errors }; comp.VerifyEmitDiagnostics(resources, // error CS7013: Name 'LongSymbolName1' exceeds the maximum length allowed in metadata. Diagnostic(ErrorCode.ERR_MetadataNameTooLong).WithArguments(s_longSymbolName + 1).WithLocation(1, 1), // error CS7013: Name 'LongPathName2' exceeds the maximum length allowed in metadata. Diagnostic(ErrorCode.ERR_MetadataNameTooLong).WithArguments(s_longPathName + 2).WithLocation(1, 1), // error CS7013: Name 'LongSymbolName3' exceeds the maximum length allowed in metadata. Diagnostic(ErrorCode.ERR_MetadataNameTooLong).WithArguments(s_longSymbolName + 3).WithLocation(1, 1), // error CS7013: Name 'LongPathName4' exceeds the maximum length allowed in metadata. Diagnostic(ErrorCode.ERR_MetadataNameTooLong).WithArguments(s_longPathName + 4).WithLocation(1, 1)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.IO; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Microsoft.Cci; using System; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class NameLengthTests : CSharpTestBase { // Longest legal symbol name. private static readonly string s_longSymbolName = new string('A', MetadataWriter.NameLengthLimit); // Longest legal path name. private static readonly string s_longPathName = new string('A', MetadataWriter.PathLengthLimit); // Longest legal local name. private static readonly string s_longLocalName = new string('A', MetadataWriter.PdbLengthLimit); [Fact] public void UnmangledMemberNames() { var sourceTemplate = @" using System; class Fields {{ int {0}; // Fine int {0}1; // Too long }} class FieldLikeEvents {{ event Action {0}; // Fine (except accessors) event Action {0}1; // Too long }} class CustomEvents {{ event Action {0} {{ add {{ }} remove {{ }} }} // Fine (except accessors) event Action {0}1 {{ add {{ }} remove {{ }} }} // Too long }} class AutoProperties {{ int {0} {{ get; set; }} // Fine (except accessors and backing field) int {0}1 {{ get; set; }} // Too long }} class CustomProperties {{ int {0} {{ get {{ return 0; }} set {{ }} }} // Fine (except accessors) int {0}1 {{ get {{ return 0; }} set {{ }} }} // Too long }} class Methods {{ void {0}() {{ }} // Fine void {0}1() {{ }} // Too long }} "; var source = string.Format(sourceTemplate, s_longSymbolName); var comp = CreateCompilation(source); comp.VerifyDiagnostics( // Uninteresting // (6,9): warning CS0169: The field 'Fields.LongSymbolName' is never used // int LongSymbolName; // Fine Diagnostic(ErrorCode.WRN_UnreferencedField, s_longSymbolName).WithArguments("Fields." + s_longSymbolName).WithLocation(6, 9), // (7,9): warning CS0169: The field 'Fields.LongSymbolName + 1' is never used // int LongSymbolName + 1; // Too long Diagnostic(ErrorCode.WRN_UnreferencedField, s_longSymbolName + 1).WithArguments("Fields." + s_longSymbolName + 1).WithLocation(7, 9), // (12,18): warning CS0067: The event 'FieldLikeEvents.LongSymbolName' is never used // event Action LongSymbolName; // Fine Diagnostic(ErrorCode.WRN_UnreferencedEvent, s_longSymbolName).WithArguments("FieldLikeEvents." + s_longSymbolName).WithLocation(12, 18), // (13,18): warning CS0067: The event 'FieldLikeEvents.LongSymbolName + 1' is never used // event Action LongSymbolName + 1; // Too long Diagnostic(ErrorCode.WRN_UnreferencedEvent, s_longSymbolName + 1).WithArguments("FieldLikeEvents." + s_longSymbolName + 1).WithLocation(13, 18)); comp.VerifyEmitDiagnostics( // (7,9): error CS7013: Name 'LongSymbolName + 1' exceeds the maximum length allowed in metadata. // int LongSymbolName + 1; // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(7, 9), // (12,18): error CS7013: Name 'add_LongSymbolName' exceeds the maximum length allowed in metadata. // event Action LongSymbolName; // Fine (except accessors) Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName).WithArguments("add_" + s_longSymbolName).WithLocation(12, 18), // (12,18): error CS7013: Name 'remove_LongSymbolName' exceeds the maximum length allowed in metadata. // event Action LongSymbolName; // Fine (except accessors) Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName).WithArguments("remove_" + s_longSymbolName).WithLocation(12, 18), // (13,18): error CS7013: Name 'LongSymbolName + 1' exceeds the maximum length allowed in metadata. // event Action LongSymbolName + 1; // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(13, 18), // (13,18): error CS7013: Name 'LongSymbolName + 1' exceeds the maximum length allowed in metadata. // event Action LongSymbolName + 1; // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(13, 18), // Would be nice not to report on the backing field. // (13,18): error CS7013: Name 'add_LongSymbolName + 1' exceeds the maximum length allowed in metadata. // event Action LongSymbolName + 1; // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments("add_" + s_longSymbolName + 1).WithLocation(13, 18), // (13,18): error CS7013: Name 'remove_LongSymbolName + 1' exceeds the maximum length allowed in metadata. // event Action LongSymbolName + 1; // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments("remove_" + s_longSymbolName + 1).WithLocation(13, 18), // (18,1044): error CS7013: Name 'add_LongSymbolName' exceeds the maximum length allowed in metadata. // event Action LongSymbolName { add { } remove { } } // Fine (except accessors) Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "add").WithArguments("add_" + s_longSymbolName).WithLocation(18, 1044), // (18,1052): error CS7013: Name 'remove_LongSymbolName' exceeds the maximum length allowed in metadata. // event Action LongSymbolName { add { } remove { } } // Fine (except accessors) Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "remove").WithArguments("remove_" + s_longSymbolName).WithLocation(18, 1052), // (19,18): error CS7013: Name 'LongSymbolName + 1' exceeds the maximum length allowed in metadata. // event Action LongSymbolName + 1 { add { } remove { } } // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(19, 18), // (19,1045): error CS7013: Name 'add_LongSymbolName + 1' exceeds the maximum length allowed in metadata. // event Action LongSymbolName + 1 { add { } remove { } } // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "add").WithArguments("add_" + s_longSymbolName + 1).WithLocation(19, 1045), // (19,1053): error CS7013: Name 'remove_LongSymbolName + 1' exceeds the maximum length allowed in metadata. // event Action LongSymbolName + 1 { add { } remove { } } // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "remove").WithArguments("remove_" + s_longSymbolName + 1).WithLocation(19, 1053), // (24,9): error CS7013: Name '<LongSymbolName>k__BackingField' exceeds the maximum length allowed in metadata. // int LongSymbolName { get; set; } // Fine (except accessors and backing field) Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName).WithArguments("<" + s_longSymbolName + ">k__BackingField").WithLocation(24, 9), // (24,1035): error CS7013: Name 'get_LongSymbolName' exceeds the maximum length allowed in metadata. // int LongSymbolName { get; set; } // Fine (except accessors and backing field) Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "get").WithArguments("get_" + s_longSymbolName).WithLocation(24, 1035), // (24,1040): error CS7013: Name 'set_LongSymbolName' exceeds the maximum length allowed in metadata. // int LongSymbolName { get; set; } // Fine (except accessors and backing field) Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "set").WithArguments("set_" + s_longSymbolName).WithLocation(24, 1040), // (25,9): error CS7013: Name 'LongSymbolName + 1' exceeds the maximum length allowed in metadata. // int LongSymbolName + 1 { get; set; } // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(25, 9), // (25,9): error CS7013: Name '<LongSymbolName + 1>k__BackingField' exceeds the maximum length allowed in metadata. // int LongSymbolName + 1 { get; set; } // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments("<" + s_longSymbolName + "1>k__BackingField").WithLocation(25, 9), // (25,1036): error CS7013: Name 'get_LongSymbolName + 1' exceeds the maximum length allowed in metadata. // int LongSymbolName + 1 { get; set; } // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "get").WithArguments("get_" + s_longSymbolName + 1).WithLocation(25, 1036), // (25,1041): error CS7013: Name 'set_LongSymbolName + 1' exceeds the maximum length allowed in metadata. // int LongSymbolName + 1 { get; set; } // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "set").WithArguments("set_" + s_longSymbolName + 1).WithLocation(25, 1041), // (30,1035): error CS7013: Name 'get_LongSymbolName' exceeds the maximum length allowed in metadata. // int LongSymbolName { get { return 0; } set { } } // Fine (except accessors) Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "get").WithArguments("get_" + s_longSymbolName).WithLocation(30, 1035), // (30,1053): error CS7013: Name 'set_LongSymbolName' exceeds the maximum length allowed in metadata. // int LongSymbolName { get { return 0; } set { } } // Fine (except accessors) Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "set").WithArguments("set_" + s_longSymbolName).WithLocation(30, 1053), // (31,9): error CS7013: Name 'LongSymbolName + 1' exceeds the maximum length allowed in metadata. // int LongSymbolName + 1 { get { return 0; } set { } } // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(31, 9), // (31,1036): error CS7013: Name 'get_LongSymbolName + 1' exceeds the maximum length allowed in metadata. // int LongSymbolName + 1 { get { return 0; } set { } } // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "get").WithArguments("get_" + s_longSymbolName + 1).WithLocation(31, 1036), // (31,1054): error CS7013: Name 'set_LongSymbolName + 1' exceeds the maximum length allowed in metadata. // int LongSymbolName + 1 { get { return 0; } set { } } // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "set").WithArguments("set_" + s_longSymbolName + 1).WithLocation(31, 1054), // (37,10): error CS7013: Name 'LongSymbolName + 1' exceeds the maximum length allowed in metadata. // void LongSymbolName + 1() { } // Too long Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(37, 10), // Uninteresting // (6,9): warning CS0169: The field 'Fields.LongSymbolName' is never used // int LongSymbolName; // Fine Diagnostic(ErrorCode.WRN_UnreferencedField, s_longSymbolName).WithArguments("Fields." + s_longSymbolName).WithLocation(6, 9), // (7,9): warning CS0169: The field 'Fields.LongSymbolName + 1' is never used // int LongSymbolName + 1; // Too long Diagnostic(ErrorCode.WRN_UnreferencedField, s_longSymbolName + 1).WithArguments("Fields." + s_longSymbolName + 1).WithLocation(7, 9), // (12,18): warning CS0067: The event 'FieldLikeEvents.LongSymbolName' is never used // event Action LongSymbolName; // Fine Diagnostic(ErrorCode.WRN_UnreferencedEvent, s_longSymbolName).WithArguments("FieldLikeEvents." + s_longSymbolName).WithLocation(12, 18), // (13,18): warning CS0067: The event 'FieldLikeEvents.LongSymbolName + 1' is never used // event Action LongSymbolName + 1; // Too long Diagnostic(ErrorCode.WRN_UnreferencedEvent, s_longSymbolName + 1).WithArguments("FieldLikeEvents." + s_longSymbolName + 1).WithLocation(13, 18)); } [Fact] public void EmptyNamespaces() { var sourceTemplate = @" namespace {0} {{ }} // Fine. namespace {0}1 {{ }} // Too long, but not checked. "; var source = string.Format(sourceTemplate, s_longSymbolName); var comp = CreateCompilation(source); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics(); } [Fact] public void NonGeneratedTypeNames() { // {n} == LongSymbolName.Substring(n) var sourceTemplate = @" class {0} {{ }} // Fine class {0}1 {{ }} // Too long namespace N {{ struct {2} {{ }} // Fine struct {2}1 {{ }} // Too long after prepending 'N.' }} class Outer {{ enum {0} {{ }} // Fine, since outer class is not prepended enum {0}1 {{ }} // Too long }} interface {2}<T> {{ }} // Fine interface {2}1<T> {{ }} // Too long after appending '`1' "; var substring0 = s_longSymbolName; var substring1 = s_longSymbolName.Substring(1); var substring2 = s_longSymbolName.Substring(2); var source = string.Format(sourceTemplate, substring0, substring1, substring2); var comp = CreateCompilation(source); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( // (3,7): // class Diagnostic(ErrorCode.ERR_MetadataNameTooLong, substring0 + 1).WithArguments(substring0 + 1).WithLocation(3, 7), // (8,12): // struct Diagnostic(ErrorCode.ERR_MetadataNameTooLong, substring2 + 1).WithArguments("N." + substring2 + 1).WithLocation(8, 12), // (14,10): // enum Diagnostic(ErrorCode.ERR_MetadataNameTooLong, substring0 + 1).WithArguments(substring0 + 1).WithLocation(14, 10), // (18,11): // interface Diagnostic(ErrorCode.ERR_MetadataNameTooLong, substring2 + 1).WithArguments(substring2 + "1`1").WithLocation(18, 11)); } [Fact] public void ExplicitInterfaceImplementation() { var sourceTemplate = @" interface I {{ void {0}(); void {0}1(); }} namespace N {{ interface J<T> {{ void {1}(); void {1}1(); }} }} class C : I, N.J<C> {{ void I.{0}() {{ }} void I.{0}1() {{ }} void N.J<C>.{1}() {{ }} void N.J<C>.{1}1() {{ }} }} "; var name0 = s_longSymbolName.Substring(2); // Space for "I." var name1 = s_longSymbolName.Substring(7); // Space for "N.J<C>." var source = string.Format(sourceTemplate, name0, name1); var comp = CreateCompilation(source); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( // (20,12): // void I.{0}1() { } Diagnostic(ErrorCode.ERR_MetadataNameTooLong, name0 + 1).WithArguments("I." + name0 + 1).WithLocation(20, 12), // (23,17): // void N.J<C>.{1}1() { } Diagnostic(ErrorCode.ERR_MetadataNameTooLong, name1 + 1).WithArguments("N.J<C>." + name1 + 1).WithLocation(23, 17)); } [Fact] public void DllImport() { var sourceTemplate = @" using System.Runtime.InteropServices; class C1 {{ [DllImport(""goo.dll"", EntryPoint = ""Short1"")] static extern void {0}(); // Name is fine, entrypoint is fine. [DllImport(""goo.dll"", EntryPoint = ""Short2"")] static extern void {0}1(); // Name is too long, entrypoint is fine. }} class C2 {{ [DllImport(""goo.dll"", EntryPoint = ""{0}"")] static extern void Short1(); // Name is fine, entrypoint is fine. [DllImport(""goo.dll"", EntryPoint = ""{0}1"")] static extern void Short2(); // Name is fine, entrypoint is too long. }} class C3 {{ [DllImport(""goo.dll"")] static extern void {0}(); // Name is fine, entrypoint is unspecified. [DllImport(""goo.dll"")] static extern void {0}1(); // Name is too long, entrypoint is unspecified. }} "; var source = string.Format(sourceTemplate, s_longSymbolName); var comp = CreateCompilation(source); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( // (9,24): Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(9, 24), // (17,24): Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "Short2").WithArguments(s_longSymbolName + 1).WithLocation(17, 24), // (25,24): Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(25, 24)); } [Fact] public void Parameters() { var sourceTemplate = @" class C {{ void M(bool {0}) {{ }} void M(long {0}1) {{ }} int this[bool {0}] {{ get {{ return 0; }} }} int this[long {0}1] {{ get {{ return 0; }} }} delegate void D1(bool {0}); delegate void D2(long {0}1); }} "; var source = string.Format(sourceTemplate, s_longSymbolName); var comp = CreateCompilation(source); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( // (5,17): error CS7013: Name 'LongSymbolName + 1' exceeds the maximum length allowed in metadata. // void M(long LongSymbolName + 1) { } Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(5, 17), // (7,19): error CS7013: Name 'LongSymbolName + 1' exceeds the maximum length allowed in metadata. // int this[long LongSymbolName + 1] { get { return 0; } } Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(7, 19), // (9,27): error CS7013: Name 'LongSymbolName + 1' exceeds the maximum length allowed in metadata. // delegate void D2(long LongSymbolName + 1); Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(9, 27), // (9,27): error CS7013: Name 'LongSymbolName + 1' exceeds the maximum length allowed in metadata. // delegate void D2(long LongSymbolName + 1); Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(9, 27)); // Second report is for Invoke method. Not ideal, but not urgent. } [Fact] public void TypeParameters() { var sourceTemplate = @" class C<{0}, {0}1> {{ }} delegate void D<{0}, {0}1>(); class E {{ void M<{0}, {0}1>() {{ }} }} "; var source = string.Format(sourceTemplate, s_longSymbolName); var comp = CreateCompilation(source); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( // (2,1034): error CS7013: Name 'LongSymbolName + 1' exceeds the maximum length allowed in metadata. // class C<LongSymbolName, LongSymbolName + 1> Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(2, 1034), // (6,1042): error CS7013: Name 'LongSymbolName + 1' exceeds the maximum length allowed in metadata. // delegate void D<LongSymbolName, LongSymbolName + 1>(); Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(6, 1042), // (10,1037): error CS7013: Name 'LongSymbolName + 1' exceeds the maximum length allowed in metadata. // void M<LongSymbolName, LongSymbolName + 1>() { } Diagnostic(ErrorCode.ERR_MetadataNameTooLong, s_longSymbolName + 1).WithArguments(s_longSymbolName + 1).WithLocation(10, 1037)); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void Locals() { var sourceTemplate = @" class C {{ int M() {{ int {0} = 1; int {0}1 = 1; return {0} + {0}1; }} }} "; var source = string.Format(sourceTemplate, s_longLocalName); var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( options: TestOptions.NativePdbEmit, // (7,13): warning CS8029: Local name 'LongLocalName + 1' is too long for PDB. Consider shortening or compiling without /debug. // int LongSymbolName + 1 = 1; Diagnostic(ErrorCode.WRN_PdbLocalNameTooLong, s_longLocalName + 1).WithArguments(s_longLocalName + 1).WithLocation(7, 13)); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)] public void ConstantLocals() { var sourceTemplate = @" class C {{ int M() {{ const int {0} = 1; const int {0}1 = 1; return {0} + {0}1; }} }} "; var source = string.Format(sourceTemplate, s_longLocalName); var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( options: TestOptions.NativePdbEmit, // (7,19): warning CS8029: Local name 'LongSymbolName + 1' is too long for PDB. Consider shortening or compiling without /debug. // const int LongSymbolName + 1 = 1; Diagnostic(ErrorCode.WRN_PdbLocalNameTooLong, s_longLocalName + 1).WithArguments(s_longLocalName + 1).WithLocation(7, 19)); } [Fact] public void TestLambdaMethods() { var sourceTemplate = @" using System; class C {{ Func<int> {0}(int p) {{ return () => p - 1; }} Func<int> {0}1(int p) {{ return () => p + 1; }} }} "; int padding = GeneratedNames.MakeLambdaMethodName("A", -1, 0, 0, 0).Length - 1; string longName = s_longSymbolName.Substring(padding); var source = string.Format(sourceTemplate, longName); var comp = CreateCompilation(source); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( // (13,16): error CS7013: Name '<longName + 1>b__3' exceeds the maximum length allowed in metadata. // return () => p + 1; Diagnostic(ErrorCode.ERR_MetadataNameTooLong, "() => p + 1").WithArguments("<" + longName + "1>b__0").WithLocation(13, 16)); } [Fact] public void TestAnonymousTypeProperties() { var sourceTemplate = @" class C {{ object M() {{ return new {{ {0} = 1, {0}1 = 'a' }}; }} }} "; int padding = GeneratedNames.MakeAnonymousTypeBackingFieldName("A").Length - 1; string longName = s_longSymbolName.Substring(padding); var source = string.Format(sourceTemplate, longName); var comp = CreateCompilation(source); comp.VerifyDiagnostics(); // CONSIDER: Double reporting (once for field def, once for member ref) is not ideal. // CONSIDER: No location since the synthesized field symbol doesn't have one (would light up automatically). comp.VerifyEmitDiagnostics( // error CS7013: Name '<longName1>i__Field' exceeds the maximum length allowed in metadata. Diagnostic(ErrorCode.ERR_MetadataNameTooLong).WithArguments("<" + longName + 1 + ">i__Field").WithLocation(1, 1), // error CS7013: Name '<longName1>i__Field' exceeds the maximum length allowed in metadata. Diagnostic(ErrorCode.ERR_MetadataNameTooLong).WithArguments("<" + longName + 1 + ">i__Field").WithLocation(1, 1)); } [Fact] public void TestStateMachineMethods() { var sourceTemplate = @" using System.Collections.Generic; using System.Threading.Tasks; class Iterators {{ IEnumerable<int> {0}() {{ yield return 1; }} IEnumerable<int> {0}1() {{ yield return 1; }} }} class Async {{ async Task {0}() {{ await {0}(); }} async Task {0}1() {{ await {0}1(); }} }} "; int padding = GeneratedNames.MakeStateMachineTypeName("A", 0, 0).Length - 1; string longName = s_longSymbolName.Substring(padding); var source = string.Format(sourceTemplate, longName); var comp = CreateCompilationWithMscorlib45(source); comp.VerifyDiagnostics(); // CONSIDER: Location would light up if synthesized methods had them. comp.VerifyEmitDiagnostics( // error CS7013: Name '<longName1>d__1' exceeds the maximum length allowed in metadata. Diagnostic(ErrorCode.ERR_MetadataNameTooLong).WithArguments("<" + longName + 1 + ">d__1").WithLocation(1, 1), // error CS7013: Name '<longName1>d__1' exceeds the maximum length allowed in metadata. Diagnostic(ErrorCode.ERR_MetadataNameTooLong).WithArguments("<" + longName + 1 + ">d__1").WithLocation(1, 1)); } [WorkItem(531484, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531484")] [Fact] public void TestFixedSizeBuffers() { var sourceTemplate = @" unsafe struct S {{ fixed int {0}[1]; fixed int {0}1[1]; }} "; int padding = GeneratedNames.MakeFixedFieldImplementationName("A").Length - 1; string longName = s_longSymbolName.Substring(padding); var source = string.Format(sourceTemplate, longName); var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics(); // CONSIDER: Location would light up if synthesized methods had them. comp.VerifyEmitDiagnostics( // error CS7013: Name '<longName1>e__FixedBuffer' exceeds the maximum length allowed in metadata. Diagnostic(ErrorCode.ERR_MetadataNameTooLong).WithArguments("<" + longName + 1 + ">e__FixedBuffer").WithLocation(1, 1)); } [Fact] public void TestResources() { var source = "class C { }"; var comp = CreateCompilation(source); Func<Stream> dataProvider = () => new System.IO.MemoryStream(); var resources = new[] { new ResourceDescription("name1", "path1", dataProvider, false), //fine new ResourceDescription(s_longSymbolName, "path2", dataProvider, false), //fine new ResourceDescription("name2", s_longPathName, dataProvider, false), //fine new ResourceDescription(s_longSymbolName + 1, "path3", dataProvider, false), //name error new ResourceDescription("name3", s_longPathName + 2, dataProvider, false), //path error new ResourceDescription(s_longSymbolName + 3, s_longPathName + 4, dataProvider, false), //name and path errors }; comp.VerifyEmitDiagnostics(resources, // error CS7013: Name 'LongSymbolName1' exceeds the maximum length allowed in metadata. Diagnostic(ErrorCode.ERR_MetadataNameTooLong).WithArguments(s_longSymbolName + 1).WithLocation(1, 1), // error CS7013: Name 'LongPathName2' exceeds the maximum length allowed in metadata. Diagnostic(ErrorCode.ERR_MetadataNameTooLong).WithArguments(s_longPathName + 2).WithLocation(1, 1), // error CS7013: Name 'LongSymbolName3' exceeds the maximum length allowed in metadata. Diagnostic(ErrorCode.ERR_MetadataNameTooLong).WithArguments(s_longSymbolName + 3).WithLocation(1, 1), // error CS7013: Name 'LongPathName4' exceeds the maximum length allowed in metadata. Diagnostic(ErrorCode.ERR_MetadataNameTooLong).WithArguments(s_longPathName + 4).WithLocation(1, 1)); } } }
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/MSBuild/PublicAPI.Shipped.txt
Microsoft.CodeAnalysis.Host.Mef.MSBuildMefHostServices Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.AssociateFileExtensionWithLanguage(string projectFileExtension, string language) -> void Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.LoadMetadataForReferencedProjects.get -> bool Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.LoadMetadataForReferencedProjects.set -> void Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.LoadProjectInfoAsync(string projectFilePath, Microsoft.CodeAnalysis.MSBuild.ProjectMap projectMap = null, System.IProgress<Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress> progress = null, Microsoft.Build.Framework.ILogger msbuildLogger = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ProjectInfo>> Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.LoadSolutionInfoAsync(string solutionFilePath, System.IProgress<Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress> progress = null, Microsoft.Build.Framework.ILogger msbuildLogger = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.SolutionInfo> Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.MSBuildProjectLoader(Microsoft.CodeAnalysis.Workspace workspace, System.Collections.Immutable.ImmutableDictionary<string, string> properties = null) -> void Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.Properties.get -> System.Collections.Immutable.ImmutableDictionary<string, string> Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.SkipUnrecognizedProjects.get -> bool Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.SkipUnrecognizedProjects.set -> void Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.AssociateFileExtensionWithLanguage(string projectFileExtension, string language) -> void Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.CloseSolution() -> void Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Diagnostics.get -> System.Collections.Immutable.ImmutableList<Microsoft.CodeAnalysis.WorkspaceDiagnostic> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.LoadMetadataForReferencedProjects.get -> bool Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.LoadMetadataForReferencedProjects.set -> void Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.OpenProjectAsync(string projectFilePath, Microsoft.Build.Framework.ILogger msbuildLogger, System.IProgress<Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress> progress = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Project> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.OpenProjectAsync(string projectFilePath, System.IProgress<Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress> progress = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Project> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.OpenSolutionAsync(string solutionFilePath, Microsoft.Build.Framework.ILogger msbuildLogger, System.IProgress<Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress> progress = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Solution> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.OpenSolutionAsync(string solutionFilePath, System.IProgress<Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress> progress = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Solution> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Properties.get -> System.Collections.Immutable.ImmutableDictionary<string, string> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.SkipUnrecognizedProjects.get -> bool Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.SkipUnrecognizedProjects.set -> void Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation.Build = 1 -> Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation.Evaluate = 0 -> Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation.Resolve = 2 -> Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress.ElapsedTime.get -> System.TimeSpan Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress.FilePath.get -> string Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress.Operation.get -> Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress.ProjectLoadProgress() -> void Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress.TargetFramework.get -> string Microsoft.CodeAnalysis.MSBuild.ProjectMap Microsoft.CodeAnalysis.MSBuild.ProjectMap.Add(Microsoft.CodeAnalysis.Project project) -> void override Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.CanApplyChange(Microsoft.CodeAnalysis.ApplyChangesKind feature) -> bool override Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.TryApplyChanges(Microsoft.CodeAnalysis.Solution newSolution) -> bool static Microsoft.CodeAnalysis.Host.Mef.MSBuildMefHostServices.DefaultAssemblies.get -> System.Collections.Immutable.ImmutableArray<System.Reflection.Assembly> static Microsoft.CodeAnalysis.Host.Mef.MSBuildMefHostServices.DefaultServices.get -> Microsoft.CodeAnalysis.Host.Mef.MefHostServices static Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create() -> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace static Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create(Microsoft.CodeAnalysis.Host.HostServices hostServices) -> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace static Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create(System.Collections.Generic.IDictionary<string, string> properties) -> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace static Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create(System.Collections.Generic.IDictionary<string, string> properties, Microsoft.CodeAnalysis.Host.HostServices hostServices) -> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace static Microsoft.CodeAnalysis.MSBuild.ProjectMap.Create() -> Microsoft.CodeAnalysis.MSBuild.ProjectMap static Microsoft.CodeAnalysis.MSBuild.ProjectMap.Create(Microsoft.CodeAnalysis.Solution solution) -> Microsoft.CodeAnalysis.MSBuild.ProjectMap
Microsoft.CodeAnalysis.Host.Mef.MSBuildMefHostServices Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.AssociateFileExtensionWithLanguage(string projectFileExtension, string language) -> void Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.LoadMetadataForReferencedProjects.get -> bool Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.LoadMetadataForReferencedProjects.set -> void Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.LoadProjectInfoAsync(string projectFilePath, Microsoft.CodeAnalysis.MSBuild.ProjectMap projectMap = null, System.IProgress<Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress> progress = null, Microsoft.Build.Framework.ILogger msbuildLogger = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<System.Collections.Immutable.ImmutableArray<Microsoft.CodeAnalysis.ProjectInfo>> Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.LoadSolutionInfoAsync(string solutionFilePath, System.IProgress<Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress> progress = null, Microsoft.Build.Framework.ILogger msbuildLogger = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.SolutionInfo> Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.MSBuildProjectLoader(Microsoft.CodeAnalysis.Workspace workspace, System.Collections.Immutable.ImmutableDictionary<string, string> properties = null) -> void Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.Properties.get -> System.Collections.Immutable.ImmutableDictionary<string, string> Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.SkipUnrecognizedProjects.get -> bool Microsoft.CodeAnalysis.MSBuild.MSBuildProjectLoader.SkipUnrecognizedProjects.set -> void Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.AssociateFileExtensionWithLanguage(string projectFileExtension, string language) -> void Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.CloseSolution() -> void Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Diagnostics.get -> System.Collections.Immutable.ImmutableList<Microsoft.CodeAnalysis.WorkspaceDiagnostic> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.LoadMetadataForReferencedProjects.get -> bool Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.LoadMetadataForReferencedProjects.set -> void Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.OpenProjectAsync(string projectFilePath, Microsoft.Build.Framework.ILogger msbuildLogger, System.IProgress<Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress> progress = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Project> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.OpenProjectAsync(string projectFilePath, System.IProgress<Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress> progress = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Project> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.OpenSolutionAsync(string solutionFilePath, Microsoft.Build.Framework.ILogger msbuildLogger, System.IProgress<Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress> progress = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Solution> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.OpenSolutionAsync(string solutionFilePath, System.IProgress<Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress> progress = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task<Microsoft.CodeAnalysis.Solution> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Properties.get -> System.Collections.Immutable.ImmutableDictionary<string, string> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.SkipUnrecognizedProjects.get -> bool Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.SkipUnrecognizedProjects.set -> void Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation.Build = 1 -> Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation.Evaluate = 0 -> Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation.Resolve = 2 -> Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress.ElapsedTime.get -> System.TimeSpan Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress.FilePath.get -> string Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress.Operation.get -> Microsoft.CodeAnalysis.MSBuild.ProjectLoadOperation Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress.ProjectLoadProgress() -> void Microsoft.CodeAnalysis.MSBuild.ProjectLoadProgress.TargetFramework.get -> string Microsoft.CodeAnalysis.MSBuild.ProjectMap Microsoft.CodeAnalysis.MSBuild.ProjectMap.Add(Microsoft.CodeAnalysis.Project project) -> void override Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.CanApplyChange(Microsoft.CodeAnalysis.ApplyChangesKind feature) -> bool override Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.TryApplyChanges(Microsoft.CodeAnalysis.Solution newSolution) -> bool static Microsoft.CodeAnalysis.Host.Mef.MSBuildMefHostServices.DefaultAssemblies.get -> System.Collections.Immutable.ImmutableArray<System.Reflection.Assembly> static Microsoft.CodeAnalysis.Host.Mef.MSBuildMefHostServices.DefaultServices.get -> Microsoft.CodeAnalysis.Host.Mef.MefHostServices static Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create() -> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace static Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create(Microsoft.CodeAnalysis.Host.HostServices hostServices) -> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace static Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create(System.Collections.Generic.IDictionary<string, string> properties) -> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace static Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create(System.Collections.Generic.IDictionary<string, string> properties, Microsoft.CodeAnalysis.Host.HostServices hostServices) -> Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace static Microsoft.CodeAnalysis.MSBuild.ProjectMap.Create() -> Microsoft.CodeAnalysis.MSBuild.ProjectMap static Microsoft.CodeAnalysis.MSBuild.ProjectMap.Create(Microsoft.CodeAnalysis.Solution solution) -> Microsoft.CodeAnalysis.MSBuild.ProjectMap
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Portable/BoundTree/BoundQuerySource.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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundQuerySource Public Sub New(source As BoundExpression) Me.New(source.Syntax, source, source.Type) Debug.Assert(source.IsValue() AndAlso Not source.IsLValue) End Sub Public Overrides ReadOnly Property ExpressionSymbol As Symbol Get Return Expression.ExpressionSymbol End Get End Property Public Overrides ReadOnly Property ResultKind As LookupResultKind Get Return Expression.ResultKind 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 Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundQuerySource Public Sub New(source As BoundExpression) Me.New(source.Syntax, source, source.Type) Debug.Assert(source.IsValue() AndAlso Not source.IsLValue) End Sub Public Overrides ReadOnly Property ExpressionSymbol As Symbol Get Return Expression.ExpressionSymbol End Get End Property Public Overrides ReadOnly Property ResultKind As LookupResultKind Get Return Expression.ResultKind End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/Diagnostics/PredefinedBuildTools.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.Diagnostics { internal static class PredefinedBuildTools { public static readonly string Build = FeaturesResources.Compiler2; public static readonly string Live = FeaturesResources.Live; } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics { internal static class PredefinedBuildTools { public static readonly string Build = FeaturesResources.Compiler2; public static readonly string Live = FeaturesResources.Live; } }
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Tools/Source/RunTests/TestRunner.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.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security; using System.Text; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json; namespace RunTests { internal struct RunAllResult { internal bool Succeeded { get; } internal ImmutableArray<TestResult> TestResults { get; } internal ImmutableArray<ProcessResult> ProcessResults { get; } internal RunAllResult(bool succeeded, ImmutableArray<TestResult> testResults, ImmutableArray<ProcessResult> processResults) { Succeeded = succeeded; TestResults = testResults; ProcessResults = processResults; } } internal sealed class TestRunner { private readonly ProcessTestExecutor _testExecutor; private readonly Options _options; internal TestRunner(Options options, ProcessTestExecutor testExecutor) { _testExecutor = testExecutor; _options = options; } internal async Task<RunAllResult> RunAllOnHelixAsync(IEnumerable<AssemblyInfo> assemblyInfoList, CancellationToken cancellationToken) { var sourceBranch = Environment.GetEnvironmentVariable("BUILD_SOURCEBRANCH"); if (sourceBranch is null) { sourceBranch = "local"; ConsoleUtil.WriteLine($@"BUILD_SOURCEBRANCH environment variable was not set. Using source branch ""{sourceBranch}"" instead"); Environment.SetEnvironmentVariable("BUILD_SOURCEBRANCH", sourceBranch); } var msbuildTestPayloadRoot = Path.GetDirectoryName(_options.ArtifactsDirectory); if (msbuildTestPayloadRoot is null) { throw new IOException($@"Malformed ArtifactsDirectory in options: ""{_options.ArtifactsDirectory}"""); } var isAzureDevOpsRun = Environment.GetEnvironmentVariable("SYSTEM_ACCESSTOKEN") is not null; if (!isAzureDevOpsRun) { ConsoleUtil.WriteLine("SYSTEM_ACCESSTOKEN environment variable was not set, so test results will not be published."); // in a local run we assume the user runs using the root test.sh and that the test payload is nested in the artifacts directory. msbuildTestPayloadRoot = Path.Combine(msbuildTestPayloadRoot, "artifacts/testPayload"); } var duplicateDir = Path.Combine(msbuildTestPayloadRoot, ".duplicate"); var correlationPayload = $@"<HelixCorrelationPayload Include=""{duplicateDir}"" />"; // https://github.com/dotnet/roslyn/issues/50661 // it's possible we should be using the BUILD_SOURCEVERSIONAUTHOR instead here a la https://github.com/dotnet/arcade/blob/main/src/Microsoft.DotNet.Helix/Sdk/tools/xharness-runner/Readme.md#how-to-use // however that variable isn't documented at https://docs.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops&tabs=yaml var queuedBy = Environment.GetEnvironmentVariable("BUILD_QUEUEDBY"); if (queuedBy is null) { queuedBy = "roslyn"; ConsoleUtil.WriteLine($@"BUILD_QUEUEDBY environment variable was not set. Using value ""{queuedBy}"" instead"); } var jobName = Environment.GetEnvironmentVariable("SYSTEM_JOBDISPLAYNAME"); if (jobName is null) { ConsoleUtil.WriteLine($"SYSTEM_JOBDISPLAYNAME environment variable was not set. Using a blank TestRunNamePrefix for Helix job."); } if (Environment.GetEnvironmentVariable("BUILD_REPOSITORY_NAME") is null) Environment.SetEnvironmentVariable("BUILD_REPOSITORY_NAME", "dotnet/roslyn"); if (Environment.GetEnvironmentVariable("SYSTEM_TEAMPROJECT") is null) Environment.SetEnvironmentVariable("SYSTEM_TEAMPROJECT", "dnceng"); if (Environment.GetEnvironmentVariable("BUILD_REASON") is null) Environment.SetEnvironmentVariable("BUILD_REASON", "pr"); var buildNumber = Environment.GetEnvironmentVariable("BUILD_BUILDNUMBER") ?? "0"; var workItems = assemblyInfoList.Select(ai => makeHelixWorkItemProject(ai)); var globalJson = JsonConvert.DeserializeAnonymousType(File.ReadAllText(getGlobalJsonPath()), new { sdk = new { version = "" } }); var project = @" <Project Sdk=""Microsoft.DotNet.Helix.Sdk"" DefaultTargets=""Test""> <PropertyGroup> <TestRunNamePrefix>" + jobName + @"_</TestRunNamePrefix> <HelixSource>pr/" + sourceBranch + @"</HelixSource> <HelixType>test</HelixType> <HelixBuild>" + buildNumber + @"</HelixBuild> <HelixTargetQueues>" + _options.HelixQueueName + @"</HelixTargetQueues> <Creator>" + queuedBy + @"</Creator> <IncludeDotNetCli>true</IncludeDotNetCli> <DotNetCliVersion>" + globalJson.sdk.version + @"</DotNetCliVersion> <DotNetCliPackageType>sdk</DotNetCliPackageType> <EnableAzurePipelinesReporter>" + (isAzureDevOpsRun ? "true" : "false") + @"</EnableAzurePipelinesReporter> </PropertyGroup> <ItemGroup> " + correlationPayload + string.Join("", workItems) + @" </ItemGroup> </Project> "; File.WriteAllText("helix-tmp.csproj", project); var process = ProcessRunner.CreateProcess( executable: _options.DotnetFilePath, arguments: "build helix-tmp.csproj", captureOutput: true, onOutputDataReceived: (e) => ConsoleUtil.WriteLine(e.Data), cancellationToken: cancellationToken); var result = await process.Result; return new RunAllResult(result.ExitCode == 0, ImmutableArray<TestResult>.Empty, ImmutableArray.Create(result)); static string getGlobalJsonPath() { var path = AppContext.BaseDirectory; while (path is object) { var globalJsonPath = Path.Join(path, "global.json"); if (File.Exists(globalJsonPath)) { return globalJsonPath; } path = Path.GetDirectoryName(path); } throw new IOException($@"Could not find global.json by walking up from ""{AppContext.BaseDirectory}""."); } string makeHelixWorkItemProject(AssemblyInfo assemblyInfo) { // Currently, it's required for the client machine to use the same OS family as the target Helix queue. // We could relax this and allow for example Linux clients to kick off Windows jobs, but we'd have to // figure out solutions for issues such as creating file paths in the correct format for the target machine. var isUnix = !RuntimeInformation.IsOSPlatform(OSPlatform.Windows); var commandLineArguments = _testExecutor.GetCommandLineArguments(assemblyInfo, useSingleQuotes: isUnix); commandLineArguments = SecurityElement.Escape(commandLineArguments); var rehydrateFilename = isUnix ? "rehydrate.sh" : "rehydrate.cmd"; var lsCommand = isUnix ? "ls" : "dir"; var rehydrateCommand = isUnix ? $"./{rehydrateFilename}" : $@"call .\{rehydrateFilename}"; var setRollforward = $"{(isUnix ? "export" : "set")} DOTNET_ROLL_FORWARD=LatestMajor"; var setPrereleaseRollforward = $"{(isUnix ? "export" : "set")} DOTNET_ROLL_FORWARD_TO_PRERELEASE=1"; var setTestIOperation = Environment.GetEnvironmentVariable("ROSLYN_TEST_IOPERATION") is { } iop ? $"{(isUnix ? "export" : "set")} ROSLYN_TEST_IOPERATION={iop}" : ""; var workItem = $@" <HelixWorkItem Include=""{assemblyInfo.DisplayName}""> <PayloadDirectory>{Path.Combine(msbuildTestPayloadRoot, Path.GetDirectoryName(assemblyInfo.AssemblyPath)!)}</PayloadDirectory> <Command> {lsCommand} {rehydrateCommand} {lsCommand} {setRollforward} {setPrereleaseRollforward} dotnet --info {setTestIOperation} dotnet {commandLineArguments} </Command> <Timeout>00:15:00</Timeout> </HelixWorkItem> "; return workItem; } } internal async Task<RunAllResult> RunAllAsync(IEnumerable<AssemblyInfo> assemblyInfoList, CancellationToken cancellationToken) { // Use 1.5 times the number of processors for unit tests, but only 1 processor for the open integration tests // since they perform actual UI operations (such as mouse clicks and sending keystrokes) and we don't want two // tests to conflict with one-another. var max = _options.Sequential ? 1 : (int)(Environment.ProcessorCount * 1.5); var waiting = new Stack<AssemblyInfo>(assemblyInfoList); var running = new List<Task<TestResult>>(); var completed = new List<TestResult>(); var failures = 0; do { cancellationToken.ThrowIfCancellationRequested(); var i = 0; while (i < running.Count) { var task = running[i]; if (task.IsCompleted) { try { var testResult = await task.ConfigureAwait(false); if (!testResult.Succeeded) { failures++; if (testResult.ResultsDisplayFilePath is string resultsPath) { ConsoleUtil.WriteLine(ConsoleColor.Red, resultsPath); } else { foreach (var result in testResult.ProcessResults) { foreach (var line in result.ErrorLines) { ConsoleUtil.WriteLine(ConsoleColor.Red, line); } } } } completed.Add(testResult); } catch (Exception ex) { ConsoleUtil.WriteLine(ConsoleColor.Red, $"Error: {ex.Message}"); failures++; } running.RemoveAt(i); } else { i++; } } while (running.Count < max && waiting.Count > 0) { var task = _testExecutor.RunTestAsync(waiting.Pop(), cancellationToken); running.Add(task); } // Display the current status of the TestRunner. // Note: The { ... , 2 } is to right align the values, thus aligns sections into columns. ConsoleUtil.Write($" {running.Count,2} running, {waiting.Count,2} queued, {completed.Count,2} completed"); if (failures > 0) { ConsoleUtil.Write($", {failures,2} failures"); } ConsoleUtil.WriteLine(); if (running.Count > 0) { await Task.WhenAny(running.ToArray()); } } while (running.Count > 0); Print(completed); var processResults = ImmutableArray.CreateBuilder<ProcessResult>(); foreach (var c in completed) { processResults.AddRange(c.ProcessResults); } return new RunAllResult((failures == 0), completed.ToImmutableArray(), processResults.ToImmutable()); } private void Print(List<TestResult> testResults) { testResults.Sort((x, y) => x.Elapsed.CompareTo(y.Elapsed)); foreach (var testResult in testResults.Where(x => !x.Succeeded)) { PrintFailedTestResult(testResult); } ConsoleUtil.WriteLine("================"); var line = new StringBuilder(); foreach (var testResult in testResults) { line.Length = 0; var color = testResult.Succeeded ? Console.ForegroundColor : ConsoleColor.Red; line.Append($"{testResult.DisplayName,-75}"); line.Append($" {(testResult.Succeeded ? "PASSED" : "FAILED")}"); line.Append($" {testResult.Elapsed}"); line.Append($" {(!string.IsNullOrEmpty(testResult.Diagnostics) ? "?" : "")}"); var message = line.ToString(); ConsoleUtil.WriteLine(color, message); } ConsoleUtil.WriteLine("================"); // Print diagnostics out last so they are cleanly visible at the end of the test summary ConsoleUtil.WriteLine("Extra run diagnostics for logging, did not impact run results"); foreach (var testResult in testResults.Where(x => !string.IsNullOrEmpty(x.Diagnostics))) { ConsoleUtil.WriteLine(testResult.Diagnostics!); } } private void PrintFailedTestResult(TestResult testResult) { // Save out the error output for easy artifact inspecting var outputLogPath = Path.Combine(_options.LogFilesDirectory, $"xUnitFailure-{testResult.DisplayName}.log"); ConsoleUtil.WriteLine($"Errors {testResult.AssemblyName}"); ConsoleUtil.WriteLine(testResult.ErrorOutput); // TODO: Put this in the log and take it off the ConsoleUtil output to keep it simple? ConsoleUtil.WriteLine($"Command: {testResult.CommandLine}"); ConsoleUtil.WriteLine($"xUnit output log: {outputLogPath}"); File.WriteAllText(outputLogPath, testResult.StandardOutput ?? ""); if (!string.IsNullOrEmpty(testResult.ErrorOutput)) { ConsoleUtil.WriteLine(testResult.ErrorOutput); } else { ConsoleUtil.WriteLine($"xunit produced no error output but had exit code {testResult.ExitCode}. Writing standard output:"); ConsoleUtil.WriteLine(testResult.StandardOutput ?? "(no standard output)"); } // If the results are html, use Process.Start to open in the browser. var htmlResultsFilePath = testResult.TestResultInfo.HtmlResultsFilePath; if (!string.IsNullOrEmpty(htmlResultsFilePath)) { var startInfo = new ProcessStartInfo() { FileName = htmlResultsFilePath, UseShellExecute = true }; Process.Start(startInfo); } } } }
// Licensed to the .NET Foundation under one or more 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.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security; using System.Text; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json; namespace RunTests { internal struct RunAllResult { internal bool Succeeded { get; } internal ImmutableArray<TestResult> TestResults { get; } internal ImmutableArray<ProcessResult> ProcessResults { get; } internal RunAllResult(bool succeeded, ImmutableArray<TestResult> testResults, ImmutableArray<ProcessResult> processResults) { Succeeded = succeeded; TestResults = testResults; ProcessResults = processResults; } } internal sealed class TestRunner { private readonly ProcessTestExecutor _testExecutor; private readonly Options _options; internal TestRunner(Options options, ProcessTestExecutor testExecutor) { _testExecutor = testExecutor; _options = options; } internal async Task<RunAllResult> RunAllOnHelixAsync(IEnumerable<AssemblyInfo> assemblyInfoList, CancellationToken cancellationToken) { var sourceBranch = Environment.GetEnvironmentVariable("BUILD_SOURCEBRANCH"); if (sourceBranch is null) { sourceBranch = "local"; ConsoleUtil.WriteLine($@"BUILD_SOURCEBRANCH environment variable was not set. Using source branch ""{sourceBranch}"" instead"); Environment.SetEnvironmentVariable("BUILD_SOURCEBRANCH", sourceBranch); } var msbuildTestPayloadRoot = Path.GetDirectoryName(_options.ArtifactsDirectory); if (msbuildTestPayloadRoot is null) { throw new IOException($@"Malformed ArtifactsDirectory in options: ""{_options.ArtifactsDirectory}"""); } var isAzureDevOpsRun = Environment.GetEnvironmentVariable("SYSTEM_ACCESSTOKEN") is not null; if (!isAzureDevOpsRun) { ConsoleUtil.WriteLine("SYSTEM_ACCESSTOKEN environment variable was not set, so test results will not be published."); // in a local run we assume the user runs using the root test.sh and that the test payload is nested in the artifacts directory. msbuildTestPayloadRoot = Path.Combine(msbuildTestPayloadRoot, "artifacts/testPayload"); } var duplicateDir = Path.Combine(msbuildTestPayloadRoot, ".duplicate"); var correlationPayload = $@"<HelixCorrelationPayload Include=""{duplicateDir}"" />"; // https://github.com/dotnet/roslyn/issues/50661 // it's possible we should be using the BUILD_SOURCEVERSIONAUTHOR instead here a la https://github.com/dotnet/arcade/blob/main/src/Microsoft.DotNet.Helix/Sdk/tools/xharness-runner/Readme.md#how-to-use // however that variable isn't documented at https://docs.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops&tabs=yaml var queuedBy = Environment.GetEnvironmentVariable("BUILD_QUEUEDBY"); if (queuedBy is null) { queuedBy = "roslyn"; ConsoleUtil.WriteLine($@"BUILD_QUEUEDBY environment variable was not set. Using value ""{queuedBy}"" instead"); } var jobName = Environment.GetEnvironmentVariable("SYSTEM_JOBDISPLAYNAME"); if (jobName is null) { ConsoleUtil.WriteLine($"SYSTEM_JOBDISPLAYNAME environment variable was not set. Using a blank TestRunNamePrefix for Helix job."); } if (Environment.GetEnvironmentVariable("BUILD_REPOSITORY_NAME") is null) Environment.SetEnvironmentVariable("BUILD_REPOSITORY_NAME", "dotnet/roslyn"); if (Environment.GetEnvironmentVariable("SYSTEM_TEAMPROJECT") is null) Environment.SetEnvironmentVariable("SYSTEM_TEAMPROJECT", "dnceng"); if (Environment.GetEnvironmentVariable("BUILD_REASON") is null) Environment.SetEnvironmentVariable("BUILD_REASON", "pr"); var buildNumber = Environment.GetEnvironmentVariable("BUILD_BUILDNUMBER") ?? "0"; var workItems = assemblyInfoList.Select(ai => makeHelixWorkItemProject(ai)); var globalJson = JsonConvert.DeserializeAnonymousType(File.ReadAllText(getGlobalJsonPath()), new { sdk = new { version = "" } }); var project = @" <Project Sdk=""Microsoft.DotNet.Helix.Sdk"" DefaultTargets=""Test""> <PropertyGroup> <TestRunNamePrefix>" + jobName + @"_</TestRunNamePrefix> <HelixSource>pr/" + sourceBranch + @"</HelixSource> <HelixType>test</HelixType> <HelixBuild>" + buildNumber + @"</HelixBuild> <HelixTargetQueues>" + _options.HelixQueueName + @"</HelixTargetQueues> <Creator>" + queuedBy + @"</Creator> <IncludeDotNetCli>true</IncludeDotNetCli> <DotNetCliVersion>" + globalJson.sdk.version + @"</DotNetCliVersion> <DotNetCliPackageType>sdk</DotNetCliPackageType> <EnableAzurePipelinesReporter>" + (isAzureDevOpsRun ? "true" : "false") + @"</EnableAzurePipelinesReporter> </PropertyGroup> <ItemGroup> " + correlationPayload + string.Join("", workItems) + @" </ItemGroup> </Project> "; File.WriteAllText("helix-tmp.csproj", project); var process = ProcessRunner.CreateProcess( executable: _options.DotnetFilePath, arguments: "build helix-tmp.csproj", captureOutput: true, onOutputDataReceived: (e) => ConsoleUtil.WriteLine(e.Data), cancellationToken: cancellationToken); var result = await process.Result; return new RunAllResult(result.ExitCode == 0, ImmutableArray<TestResult>.Empty, ImmutableArray.Create(result)); static string getGlobalJsonPath() { var path = AppContext.BaseDirectory; while (path is object) { var globalJsonPath = Path.Join(path, "global.json"); if (File.Exists(globalJsonPath)) { return globalJsonPath; } path = Path.GetDirectoryName(path); } throw new IOException($@"Could not find global.json by walking up from ""{AppContext.BaseDirectory}""."); } string makeHelixWorkItemProject(AssemblyInfo assemblyInfo) { // Currently, it's required for the client machine to use the same OS family as the target Helix queue. // We could relax this and allow for example Linux clients to kick off Windows jobs, but we'd have to // figure out solutions for issues such as creating file paths in the correct format for the target machine. var isUnix = !RuntimeInformation.IsOSPlatform(OSPlatform.Windows); var commandLineArguments = _testExecutor.GetCommandLineArguments(assemblyInfo, useSingleQuotes: isUnix); commandLineArguments = SecurityElement.Escape(commandLineArguments); var rehydrateFilename = isUnix ? "rehydrate.sh" : "rehydrate.cmd"; var lsCommand = isUnix ? "ls" : "dir"; var rehydrateCommand = isUnix ? $"./{rehydrateFilename}" : $@"call .\{rehydrateFilename}"; var setRollforward = $"{(isUnix ? "export" : "set")} DOTNET_ROLL_FORWARD=LatestMajor"; var setPrereleaseRollforward = $"{(isUnix ? "export" : "set")} DOTNET_ROLL_FORWARD_TO_PRERELEASE=1"; var setTestIOperation = Environment.GetEnvironmentVariable("ROSLYN_TEST_IOPERATION") is { } iop ? $"{(isUnix ? "export" : "set")} ROSLYN_TEST_IOPERATION={iop}" : ""; var workItem = $@" <HelixWorkItem Include=""{assemblyInfo.DisplayName}""> <PayloadDirectory>{Path.Combine(msbuildTestPayloadRoot, Path.GetDirectoryName(assemblyInfo.AssemblyPath)!)}</PayloadDirectory> <Command> {lsCommand} {rehydrateCommand} {lsCommand} {setRollforward} {setPrereleaseRollforward} dotnet --info {setTestIOperation} dotnet {commandLineArguments} </Command> <Timeout>00:15:00</Timeout> </HelixWorkItem> "; return workItem; } } internal async Task<RunAllResult> RunAllAsync(IEnumerable<AssemblyInfo> assemblyInfoList, CancellationToken cancellationToken) { // Use 1.5 times the number of processors for unit tests, but only 1 processor for the open integration tests // since they perform actual UI operations (such as mouse clicks and sending keystrokes) and we don't want two // tests to conflict with one-another. var max = _options.Sequential ? 1 : (int)(Environment.ProcessorCount * 1.5); var waiting = new Stack<AssemblyInfo>(assemblyInfoList); var running = new List<Task<TestResult>>(); var completed = new List<TestResult>(); var failures = 0; do { cancellationToken.ThrowIfCancellationRequested(); var i = 0; while (i < running.Count) { var task = running[i]; if (task.IsCompleted) { try { var testResult = await task.ConfigureAwait(false); if (!testResult.Succeeded) { failures++; if (testResult.ResultsDisplayFilePath is string resultsPath) { ConsoleUtil.WriteLine(ConsoleColor.Red, resultsPath); } else { foreach (var result in testResult.ProcessResults) { foreach (var line in result.ErrorLines) { ConsoleUtil.WriteLine(ConsoleColor.Red, line); } } } } completed.Add(testResult); } catch (Exception ex) { ConsoleUtil.WriteLine(ConsoleColor.Red, $"Error: {ex.Message}"); failures++; } running.RemoveAt(i); } else { i++; } } while (running.Count < max && waiting.Count > 0) { var task = _testExecutor.RunTestAsync(waiting.Pop(), cancellationToken); running.Add(task); } // Display the current status of the TestRunner. // Note: The { ... , 2 } is to right align the values, thus aligns sections into columns. ConsoleUtil.Write($" {running.Count,2} running, {waiting.Count,2} queued, {completed.Count,2} completed"); if (failures > 0) { ConsoleUtil.Write($", {failures,2} failures"); } ConsoleUtil.WriteLine(); if (running.Count > 0) { await Task.WhenAny(running.ToArray()); } } while (running.Count > 0); Print(completed); var processResults = ImmutableArray.CreateBuilder<ProcessResult>(); foreach (var c in completed) { processResults.AddRange(c.ProcessResults); } return new RunAllResult((failures == 0), completed.ToImmutableArray(), processResults.ToImmutable()); } private void Print(List<TestResult> testResults) { testResults.Sort((x, y) => x.Elapsed.CompareTo(y.Elapsed)); foreach (var testResult in testResults.Where(x => !x.Succeeded)) { PrintFailedTestResult(testResult); } ConsoleUtil.WriteLine("================"); var line = new StringBuilder(); foreach (var testResult in testResults) { line.Length = 0; var color = testResult.Succeeded ? Console.ForegroundColor : ConsoleColor.Red; line.Append($"{testResult.DisplayName,-75}"); line.Append($" {(testResult.Succeeded ? "PASSED" : "FAILED")}"); line.Append($" {testResult.Elapsed}"); line.Append($" {(!string.IsNullOrEmpty(testResult.Diagnostics) ? "?" : "")}"); var message = line.ToString(); ConsoleUtil.WriteLine(color, message); } ConsoleUtil.WriteLine("================"); // Print diagnostics out last so they are cleanly visible at the end of the test summary ConsoleUtil.WriteLine("Extra run diagnostics for logging, did not impact run results"); foreach (var testResult in testResults.Where(x => !string.IsNullOrEmpty(x.Diagnostics))) { ConsoleUtil.WriteLine(testResult.Diagnostics!); } } private void PrintFailedTestResult(TestResult testResult) { // Save out the error output for easy artifact inspecting var outputLogPath = Path.Combine(_options.LogFilesDirectory, $"xUnitFailure-{testResult.DisplayName}.log"); ConsoleUtil.WriteLine($"Errors {testResult.AssemblyName}"); ConsoleUtil.WriteLine(testResult.ErrorOutput); // TODO: Put this in the log and take it off the ConsoleUtil output to keep it simple? ConsoleUtil.WriteLine($"Command: {testResult.CommandLine}"); ConsoleUtil.WriteLine($"xUnit output log: {outputLogPath}"); File.WriteAllText(outputLogPath, testResult.StandardOutput ?? ""); if (!string.IsNullOrEmpty(testResult.ErrorOutput)) { ConsoleUtil.WriteLine(testResult.ErrorOutput); } else { ConsoleUtil.WriteLine($"xunit produced no error output but had exit code {testResult.ExitCode}. Writing standard output:"); ConsoleUtil.WriteLine(testResult.StandardOutput ?? "(no standard output)"); } // If the results are html, use Process.Start to open in the browser. var htmlResultsFilePath = testResult.TestResultInfo.HtmlResultsFilePath; if (!string.IsNullOrEmpty(htmlResultsFilePath)) { var startInfo = new ProcessStartInfo() { FileName = htmlResultsFilePath, UseShellExecute = true }; Process.Start(startInfo); } } } }
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/UnifiedSuggestions/UnifiedSuggestedActions/UnifiedSuggestedAction.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.CodeActions; namespace Microsoft.CodeAnalysis.UnifiedSuggestions { /// <summary> /// Similar to SuggestedAction, but in a location that can be used by /// both local Roslyn and LSP. /// </summary> internal class UnifiedSuggestedAction : IUnifiedSuggestedAction { public Workspace Workspace { get; } public CodeAction OriginalCodeAction { get; } public CodeActionPriority CodeActionPriority { get; } public UnifiedSuggestedAction(Workspace workspace, CodeAction codeAction, CodeActionPriority codeActionPriority) { Workspace = workspace; OriginalCodeAction = codeAction; CodeActionPriority = codeActionPriority; } } }
// Licensed to the .NET Foundation under one or more 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.CodeActions; namespace Microsoft.CodeAnalysis.UnifiedSuggestions { /// <summary> /// Similar to SuggestedAction, but in a location that can be used by /// both local Roslyn and LSP. /// </summary> internal class UnifiedSuggestedAction : IUnifiedSuggestedAction { public Workspace Workspace { get; } public CodeAction OriginalCodeAction { get; } public CodeActionPriority CodeActionPriority { get; } public UnifiedSuggestedAction(Workspace workspace, CodeAction codeAction, CodeActionPriority codeActionPriority) { Workspace = workspace; OriginalCodeAction = codeAction; CodeActionPriority = codeActionPriority; } } }
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxRewriterTests.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.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SyntaxRewriterTests #Region "Green Tree / SeparatedSyntaxList" <Fact> Public Sub TestGreenSeparatedDeleteNone() ' the argument list Is a SeparatedSyntaxList Dim input = "F(A,B,C)" Dim output = input Dim rewriter = New GreenRewriter() TestGreen(input, output, rewriter, isStmt:=True) End Sub <Fact> Public Sub TestGreenSeparatedDeleteSome() ' the argument list Is a SeparatedSyntaxList Dim input = "F(A,B,C)" Dim output = "F(A,C)" ' delete the middle argument (should clear the following comma) Dim rewriter = New GreenRewriter(rewriteNode:= Function(node) Return If(node.Kind = SyntaxKind.SimpleArgument AndAlso node.ToString() = "B", Nothing, node) End Function) TestGreen(input, output, rewriter, isStmt:=True) End Sub <Fact> Public Sub TestGreenSeparatedDeleteAll() ' the argument list Is a SeparatedSyntaxList Dim input = "F(A,B,C)" Dim output = "F()" ' delete all arguments, should clear the intervening commas Dim rewriter = New GreenRewriter(rewriteNode:= Function(node) Return If(node.Kind = SyntaxKind.SimpleArgument, Nothing, node) End Function) TestGreen(input, output, rewriter, isStmt:=True) End Sub #End Region ' Green Tree / SeparatedSyntaxList #Region "Green Tree / SyntaxList" <Fact> Public Sub TestGreenDeleteNone() ' class declarations constitute a SyntaxList Dim input = <![CDATA[ Class A End Class Class B End Class Class C End Class ]]>.Value Dim output = input Dim rewriter As GreenRewriter = New GreenRewriter() TestGreen(input, output, rewriter, isStmt:=False) End Sub <Fact> Public Sub TestGreenDeleteSome() ' class declarations constitute a SyntaxList Dim input = <![CDATA[ Class A End Class Class B End Class Class C End Class ]]>.Value Dim output = <![CDATA[ Class A End Class Class C End Class ]]>.Value Dim rewriter = New GreenRewriter(rewriteNode:= Function(node) Return If(node.Kind = SyntaxKind.ClassBlock AndAlso node.ToString().Contains("B"), Nothing, node) End Function) TestGreen(input, output, rewriter, isStmt:=False) End Sub <Fact> Public Sub TestGreenDeleteAll() ' class declarations constitute a SyntaxList Dim input = <![CDATA[ Class A End Class Class B End Class Class C End Class ]]>.Value Dim output = <![CDATA[ ]]>.Value ' delete all statements Dim rewriter = New GreenRewriter(rewriteNode:= Function(node) Return If(node.Kind = SyntaxKind.ClassBlock, Nothing, node) End Function) TestGreen(input, output, rewriter, isStmt:=False) End Sub #End Region ' Green Tree / SyntaxList #Region "Red Tree / SeparatedSyntaxList" <Fact> Public Sub TestRedSeparatedDeleteNone() ' the argument list Is a SeparatedSyntaxList Dim input = "F(A,B,C)" Dim output = input Dim rewriter = New RedRewriter() TestRed(input, output, rewriter, isStmt:=True) End Sub <Fact> Public Sub TestRedSeparatedDeleteSome() ' the argument list Is a SeparatedSyntaxList Dim input = "F(A,B,C)" ' delete the middle type argument (should clear the following comma) Dim rewriter = New RedRewriter(rewriteNode:= Function(node) Return If(node.Kind = SyntaxKind.SimpleArgument AndAlso node.ToString() = "B", Nothing, node) End Function) Dim caught As Exception = Nothing Try TestRed(input, "", rewriter, isStmt:=True) Catch ex As InvalidOperationException caught = ex End Try Assert.NotNull(caught) End Sub <Fact> Public Sub TestRedSeparatedDeleteAll() ' the argument list Is a SeparatedSyntaxList Dim input = "F(A,B,C)" ' delete all arguments, should clear the intervening commas Dim rewriter = New RedRewriter(rewriteNode:= Function(node) Return If(node.Kind = SyntaxKind.SimpleArgument, Nothing, node) End Function) Dim caught As Exception = Nothing Try TestRed(input, "", rewriter, isStmt:=True) Catch ex As InvalidOperationException caught = ex End Try Assert.NotNull(caught) End Sub #End Region ' Red Tree / SeparatedSyntaxList #Region "Red Tree / SyntaxTokenList" <Fact> Public Sub TestRedTokenDeleteNone() ' commas in an implicit array creation constitute a SyntaxTokenList Dim input = <![CDATA[ Class c Sub s(x as Boolean(,,)) End Sub End Class ]]>.Value Dim output = input Dim rewriter As RedRewriter = New RedRewriter() TestRed(input, output, rewriter, isStmt:=False) End Sub <Fact> Public Sub TestRedTokenDeleteSome() ' commas in an implicit array creation constitute a SyntaxTokenList Dim input = <![CDATA[ Class c Sub s(x as Boolean(,,)) End Sub End Class ]]>.Value Dim output = <![CDATA[ Class c Sub s(x as Boolean(,)) End Sub End Class ]]>.Value ' delete one comma Dim first As Boolean = True Dim rewriter = New RedRewriter(rewriteToken:= Function(token) If token.Kind = SyntaxKind.CommaToken AndAlso first Then first = False Return Nothing End If Return token End Function) TestRed(input, output, rewriter, isStmt:=False) End Sub <Fact> Public Sub TestRedTokenDeleteAll() ' commas in an implicit array creation constitute a SyntaxTokenList Dim input = <![CDATA[ Class c Sub s(x as Boolean(,,)) End Sub End Class ]]>.Value Dim output = <![CDATA[ Class c Sub s(x as Boolean()) End Sub End Class ]]>.Value ' delete all commas Dim rewriter = New RedRewriter(rewriteToken:= Function(token) Return If(token.Kind = SyntaxKind.CommaToken, Nothing, token) End Function) TestRed(input, output, rewriter, isStmt:=False) End Sub #End Region ' Red Tree / SyntaxTokenList #Region "Red Tree / SyntaxNodeOrTokenList" ' These only in the syntax tree inside SeparatedSyntaxLists, so they are not visitable. ' We can't call this directly due to its protection level. #End Region ' Red Tree / SyntaxNodeOrTokenList #Region "Red Tree / SyntaxTriviaList" <Fact> Public Sub TestRedTriviaDeleteNone() ' whitespace and comments constitute a SyntaxTriviaList Dim input = " a() ' comment" Dim output = input Dim rewriter As RedRewriter = New RedRewriter() TestRed(input, output, rewriter, isStmt:=True) End Sub <Fact> Public Sub TestRedTriviaDeleteSome() ' whitespace and comments constitute a SyntaxTriviaList Dim input = " a() ' comment" Dim output = "a()' comment" ' delete all whitespace trivia (leave comments) Dim rewriter = New RedRewriter(rewriteTrivia:= Function(trivia) Return If(trivia.Kind = SyntaxKind.WhitespaceTrivia, Nothing, trivia) End Function) TestRed(input, output, rewriter, isStmt:=True) End Sub <Fact> Public Sub TestRedTriviaDeleteAll() ' whitespace and comments constitute a SyntaxTriviaList Dim input = " a() ' comment" Dim output = "a()" ' delete all trivia Dim rewriter = New RedRewriter(rewriteTrivia:=Function(trivia) Nothing) TestRed(input, output, rewriter, isStmt:=True) End Sub #End Region ' Red Tree / SyntaxTriviaList #Region "Red Tree / SyntaxList" <Fact> Public Sub TestRedDeleteNone() ' attributes are a SyntaxList Dim input = <![CDATA[ <Attr1()> <Attr2()> <Attr3()> Class Q End Class ]]>.Value Dim output = input Dim rewriter = New RedRewriter() TestRed(input, output, rewriter, isStmt:=False) End Sub <Fact> Public Sub TestRedDeleteSome() ' attributes are a SyntaxList Dim input = <![CDATA[ <Attr1()> <Attr2()> <Attr3()> Class Q End Class ]]>.Value Dim output = <![CDATA[ <Attr1()> <Attr3()> Class Q End Class ]]>.Value Dim rewriter = New RedRewriter(rewriteNode:= Function(node) Return If(node.Kind = SyntaxKind.AttributeList AndAlso node.ToString().Contains("2"), Nothing, node) End Function) TestRed(input, output, rewriter, isStmt:=False) End Sub <Fact> Public Sub TestRedDeleteAll() ' attributes are a SyntaxList Dim input = <![CDATA[ <Attr1()> <Attr2()> <Attr3()> Class Q End Class ]]>.Value Dim output = <![CDATA[ Class Q End Class ]]>.Value Dim rewriter = New RedRewriter(rewriteNode:= Function(node) Return If(node.Kind = SyntaxKind.AttributeList, Nothing, node) End Function) TestRed(input, output, rewriter, isStmt:=False) End Sub #End Region ' Red Tree / SyntaxList #Region "Misc" <Fact> Public Sub TestRedSeparatedDeleteLast() Dim input = "F(A,B,C)" Dim output = "F(A,B,)" ' delete the last argument (should clear the *preceding* comma) Dim rewriter = New RedRewriter(rewriteNode:= Function(node) Return If(node.Kind = SyntaxKind.SimpleArgument AndAlso node.ToString() = "C", Nothing, node) End Function) TestRed(input, output, rewriter, isStmt:=True) End Sub <Fact> Public Sub TestGreenSeparatedDeleteLast() Dim input = "F(A,B,C)" Dim output = "F(A,B)" ' delete the last argument (should clear the *preceding* comma) Dim rewriter = New GreenRewriter(rewriteNode:= Function(node) Return If(node.Kind = SyntaxKind.SimpleArgument AndAlso node.ToString() = "C", Nothing, node) End Function) TestGreen(input, output, rewriter, isStmt:=True) End Sub <Fact> Public Sub TestRedSeparatedDeleteLastWithTrailingSeparator() Dim input = <![CDATA[ Class Q Sub A() End Sub Sub B() End Sub End Class ]]>.Value Dim rewriter = New RedRewriter(rewriteNode:= Function(node) Return If(node.Kind = SyntaxKind.SubBlock AndAlso node.ToString().Contains("B"), Nothing, node) End Function) Dim caught As Exception = Nothing Dim output = <![CDATA[ Class Q Sub A() End Sub End Class ]]>.Value TestRed(input, output, rewriter, isStmt:=False) End Sub <Fact> Public Sub TestGreenSeparatedDeleteLastWithTrailingSeparator() Dim input = <![CDATA[ Class Q Sub A() End Sub Sub B() End Sub End Class ]]>.Value Dim output = <![CDATA[ Class Q Sub A() End Sub End Class ]]>.Value Dim rewriter = New GreenRewriter(rewriteNode:= Function(node) Return If(node.Kind = SyntaxKind.SubBlock AndAlso node.ToString().Contains("B"), Nothing, node) End Function) TestGreen(input, output, rewriter, isStmt:=False) End Sub <Fact> Public Sub TestRedSeparatedDeleteSeparator() Dim red = SyntaxFactory.ParseExecutableStatement("F(A,B,C)") Assert.False(red.ContainsDiagnostics) Dim rewriter = New RedRewriter(rewriteToken:= Function(token) Return If(token.Kind = SyntaxKind.CommaToken, Nothing, token) End Function) Assert.Throws(Of InvalidOperationException)(Sub() rewriter.Visit(red)) End Sub <Fact> Public Sub TestCreateSyntaxTreeWithoutClone() ' Test SyntaxTree.CreateWithoutClone() implicitly invoked by accessing the SyntaxTree property. ' Ensure this API preserves reference equality of the syntax node. Dim expression = SyntaxFactory.ParseExpression("0") Dim tree = expression.SyntaxTree Assert.Same(expression, tree.GetRoot()) Assert.False(tree.HasCompilationUnitRoot, "how did we get a CompilationUnit root?") End Sub <Fact> Public Sub RemoveDocCommentNode() Dim oldSource = <![CDATA[ ''' <see cref='C'/> Class C End Class ]]> Dim expectedNewSource = <![CDATA[ ''' Class C End Class ]]> Dim oldTree = VisualBasicSyntaxTree.ParseText(oldSource.Value, options:=New VisualBasicParseOptions(documentationMode:=DocumentationMode.Diagnose)) Dim oldRoot = oldTree.GetRoot() Dim xmlNode = oldRoot.DescendantNodes(descendIntoTrivia:=True).OfType(Of XmlEmptyElementSyntax)().Single() Dim newRoot = oldRoot.RemoveNode(xmlNode, SyntaxRemoveOptions.KeepDirectives) Assert.Equal(expectedNewSource.Value, newRoot.ToFullString()) End Sub <WorkItem(991474, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991474")> <Fact> Public Sub ReturnNothingFromStructuredTriviaRoot_Succeeds() Dim Text = <x>#Region Class C End Class #End Region"</x>.Value Dim expectedText = <x>Class C End Class #End Region"</x>.Value Dim root = SyntaxFactory.ParseCompilationUnit(Text) Dim newRoot = New RemoveRegionRewriter().Visit(root) Assert.Equal(expectedText, newRoot.ToFullString()) End Sub <Fact> <WorkItem(22010, "https://github.com/dotnet/roslyn/issues/22010")> Public Sub TestReplaceNodeShouldNotLoseParseOptions() Dim tree = SyntaxFactory.ParseSyntaxTree("System.Console.Write(""Before"")", TestOptions.Script) Assert.Equal(SourceCodeKind.Script, tree.Options.Kind) Dim root = tree.GetRoot() Dim before = root.DescendantNodes().OfType(Of LiteralExpressionSyntax)().Single() Dim after = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal("After")) Dim newRoot = root.ReplaceNode(before, after) Dim newTree = newRoot.SyntaxTree Assert.Equal(SourceCodeKind.Script, newTree.Options.Kind) Assert.Equal(tree.Options, newTree.Options) End Sub <Fact> <WorkItem(22010, "https://github.com/dotnet/roslyn/issues/22010")> Public Sub TestReplaceNodeInListShouldNotLoseParseOptions() Dim tree = SyntaxFactory.ParseSyntaxTree("m(a, b)", TestOptions.Script) Assert.Equal(SourceCodeKind.Script, tree.Options.Kind) Dim argC = SyntaxFactory.SimpleArgument(SyntaxFactory.ParseExpression("c")) Dim argD = SyntaxFactory.SimpleArgument(SyntaxFactory.ParseExpression("d")) Dim root = tree.GetRoot() Dim invocation = root.DescendantNodes().OfType(Of InvocationExpressionSyntax)().Single() Dim newRoot = root.ReplaceNode(invocation.ArgumentList.Arguments(0), New SyntaxNode() {argC, argD}) Assert.Equal("m(c,d, b)", newRoot.ToFullString()) Dim newTree = newRoot.SyntaxTree Assert.Equal(SourceCodeKind.Script, newTree.Options.Kind) Assert.Equal(tree.Options, newTree.Options) End Sub <Fact> <WorkItem(22010, "https://github.com/dotnet/roslyn/issues/22010")> Public Sub TestInsertNodeShouldNotLoseParseOptions() Dim tree = SyntaxFactory.ParseSyntaxTree("m(a, b)", TestOptions.Script) Assert.Equal(SourceCodeKind.Script, tree.Options.Kind) Dim argC = SyntaxFactory.SimpleArgument(SyntaxFactory.ParseExpression("c")) Dim argD = SyntaxFactory.SimpleArgument(SyntaxFactory.ParseExpression("d")) Dim root = tree.GetRoot() Dim invocation = root.DescendantNodes().OfType(Of InvocationExpressionSyntax)().Single() ' insert before first Dim newNode = invocation.InsertNodesBefore(invocation.ArgumentList.Arguments(0), New SyntaxNode() {argC, argD}) Assert.Equal("m(c,d,a, b)", newNode.ToFullString()) Dim newTree = newNode.SyntaxTree Assert.Equal(SourceCodeKind.Script, newTree.Options.Kind) Assert.Equal(tree.Options, newTree.Options) ' insert after first Dim newNode2 = invocation.InsertNodesAfter(invocation.ArgumentList.Arguments(0), New SyntaxNode() {argC, argD}) Assert.Equal("m(a,c,d, b)", newNode2.ToFullString()) Dim newTree2 = newNode2.SyntaxTree Assert.Equal(SourceCodeKind.Script, newTree2.Options.Kind) Assert.Equal(tree.Options, newTree2.Options) End Sub <Fact> <WorkItem(22010, "https://github.com/dotnet/roslyn/issues/22010")> Public Sub TestReplaceTokenShouldNotLoseParseOptions() Dim tree = SyntaxFactory.ParseSyntaxTree("Private Class C ", options:=TestOptions.Script) Assert.Equal(SourceCodeKind.Script, tree.Options.Kind) Dim root = tree.GetRoot() Dim privateToken = root.DescendantTokens().First() Dim publicToken = SyntaxFactory.ParseToken("Public ") Dim partialToken = SyntaxFactory.ParseToken("Partial ") Dim newRoot = root.ReplaceToken(privateToken, New SyntaxToken() {publicToken, partialToken}) Assert.Equal("Public Partial Class C ", newRoot.ToFullString()) Dim newTree = newRoot.SyntaxTree Assert.Equal(SourceCodeKind.Script, newTree.Options.Kind) Assert.Equal(tree.Options, newTree.Options) End Sub <Fact> <WorkItem(22010, "https://github.com/dotnet/roslyn/issues/22010")> Public Sub TestInsertTokenShouldNotLoseParseOptions() Dim tree = SyntaxFactory.ParseSyntaxTree("Public Class C" & vbCrLf & "End Class", options:=TestOptions.Script) Dim root = tree.GetRoot() Dim publicToken = root.DescendantTokens().First() Dim partialToken = SyntaxFactory.ParseToken("Partial ") Dim staticToken = SyntaxFactory.ParseToken("Shared ") Dim newRoot = root.InsertTokensBefore(publicToken, New SyntaxToken() {staticToken}) Assert.Equal("Shared Public Class C" & vbCrLf & "End Class", newRoot.ToFullString()) Dim newTree = newRoot.SyntaxTree Assert.Equal(SourceCodeKind.Script, newTree.Options.Kind) Assert.Equal(tree.Options, newTree.Options) Dim newRoot2 = root.InsertTokensAfter(publicToken, New SyntaxToken() {staticToken}) Assert.Equal("Public Shared Class C" & vbCrLf & "End Class", newRoot2.ToFullString()) Dim newTree2 = newRoot2.SyntaxTree Assert.Equal(SourceCodeKind.Script, newTree2.Options.Kind) Assert.Equal(tree.Options, newTree2.Options) End Sub <Fact> <WorkItem(22010, "https://github.com/dotnet/roslyn/issues/22010")> Public Sub TestReplaceTriviaShouldNotLoseParseOptions() Dim tree = SyntaxFactory.ParseSyntaxTree("Dim identifier 'c", options:=TestOptions.Script) Dim field = tree.GetRoot().DescendantNodes().OfType(Of FieldDeclarationSyntax).Single() Dim trailingTrivia = field.GetTrailingTrivia() Assert.Equal(2, trailingTrivia.Count) Dim comment1 = trailingTrivia(1) Assert.Equal(SyntaxKind.CommentTrivia, comment1.Kind()) Dim newComment1 = SyntaxFactory.ParseLeadingTrivia("'a")(0) Dim newComment2 = SyntaxFactory.ParseLeadingTrivia("'b")(0) Dim newField = field.ReplaceTrivia(comment1, New SyntaxTrivia() {newComment1, newComment2}) Assert.Equal("Dim identifier 'a'b", newField.ToFullString()) Dim newTree = newField.SyntaxTree Assert.Equal(SourceCodeKind.Script, newTree.Options.Kind) Assert.Equal(tree.Options, newTree.Options) Dim newRoot2 = field.ReplaceTrivia(comment1, New SyntaxTrivia() {}) Assert.Equal("Dim identifier ", newRoot2.ToFullString()) Dim newTree2 = newRoot2.SyntaxTree Assert.Equal(SourceCodeKind.Script, newTree2.Options.Kind) Assert.Equal(tree.Options, newTree2.Options) End Sub <Fact> <WorkItem(22010, "https://github.com/dotnet/roslyn/issues/22010")> Public Sub TestInsertTriviaShouldNotLoseParseOptions() Dim tree = SyntaxFactory.ParseSyntaxTree("Dim identifier 'c", options:=TestOptions.Script) Dim field = tree.GetRoot().DescendantNodes().OfType(Of FieldDeclarationSyntax).Single() Dim trailingTrivia = field.GetTrailingTrivia() Assert.Equal(2, trailingTrivia.Count) Dim comment1 = trailingTrivia(1) Assert.Equal(SyntaxKind.CommentTrivia, comment1.Kind()) Dim newComment1 = SyntaxFactory.ParseLeadingTrivia("'a")(0) Dim newComment2 = SyntaxFactory.ParseLeadingTrivia("'b")(0) Dim newField = field.InsertTriviaAfter(comment1, New SyntaxTrivia() {newComment1, newComment2}) Assert.Equal("Dim identifier 'c'a'b", newField.ToFullString()) Dim newTree = newField.SyntaxTree Assert.Equal(SourceCodeKind.Script, newTree.Options.Kind) Assert.Equal(tree.Options, newTree.Options) End Sub <Fact> <WorkItem(22010, "https://github.com/dotnet/roslyn/issues/22010")> Public Sub TestRemoveNodeShouldNotLoseParseOptions() Dim tree = SyntaxFactory.ParseSyntaxTree("Private Class C" & vbCrLf & "End Class", options:=TestOptions.Script) Dim root = tree.GetRoot() Dim newRoot = root.RemoveNode(root.DescendantNodes().First(), SyntaxRemoveOptions.KeepDirectives) Dim newTree = newRoot.SyntaxTree Assert.Equal(SourceCodeKind.Script, newTree.Options.Kind) Assert.Equal(tree.Options, newTree.Options) End Sub <Fact> <WorkItem(22010, "https://github.com/dotnet/roslyn/issues/22010")> Public Sub TestNormalizeWhitespaceShouldNotLoseParseOptions() Dim tree = SyntaxFactory.ParseSyntaxTree("Private Class C" & vbCrLf & "End Class", options:=TestOptions.Script) Dim root = tree.GetRoot() Dim newRoot = root.NormalizeWhitespace(" ") Dim newTree = newRoot.SyntaxTree Assert.Equal(SourceCodeKind.Script, newTree.Options.Kind) Assert.Equal(tree.Options, newTree.Options) End Sub Private Class RemoveRegionRewriter Inherits VisualBasicSyntaxRewriter Public Sub New() MyBase.New(visitIntoStructuredTrivia:=True) End Sub Public Overrides Function VisitRegionDirectiveTrivia(node As RegionDirectiveTriviaSyntax) As SyntaxNode Return Nothing End Function End Class #End Region ' Misc #Region "Helper Types" Private Sub TestGreen(input As String, output As String, rewriter As GreenRewriter, isStmt As Boolean) Dim red As VisualBasicSyntaxNode If isStmt Then red = SyntaxFactory.ParseExecutableStatement(input) Else red = SyntaxFactory.ParseCompilationUnit(input) End If Dim green = red.ToGreen() Assert.False(green.ContainsDiagnostics) Dim result As InternalSyntax.VisualBasicSyntaxNode = rewriter.Visit(green) Assert.Equal(input = output, green Is result) Assert.Equal(output.Trim(), result.ToFullString().Trim()) End Sub Private Sub TestRed(input As String, output As String, rewriter As RedRewriter, isStmt As Boolean) Dim red As VisualBasicSyntaxNode If isStmt Then red = SyntaxFactory.ParseExecutableStatement(input) Else red = SyntaxFactory.ParseCompilationUnit(input) End If Assert.False(red.ContainsDiagnostics) Dim result = rewriter.Visit(red) Assert.Equal(input = output, red Is result) Assert.Equal(output.Trim(), result.ToFullString().Trim()) End Sub #End Region ' Helper Types #Region "Helper Types" ''' <summary> ''' This Rewriter exposes delegates for the methods that would normally be overridden. ''' </summary> Friend Class GreenRewriter Inherits InternalSyntax.VisualBasicSyntaxRewriter Private ReadOnly _rewriteNode As Func(Of InternalSyntax.VisualBasicSyntaxNode, InternalSyntax.VisualBasicSyntaxNode) Private ReadOnly _rewriteToken As Func(Of InternalSyntax.SyntaxToken, InternalSyntax.SyntaxToken) Private ReadOnly _rewriteTrivia As Func(Of InternalSyntax.SyntaxTrivia, InternalSyntax.SyntaxTrivia) Friend Sub New( Optional rewriteNode As Func(Of InternalSyntax.VisualBasicSyntaxNode, InternalSyntax.VisualBasicSyntaxNode) = Nothing, Optional rewriteToken As Func(Of InternalSyntax.SyntaxToken, InternalSyntax.SyntaxToken) = Nothing, Optional rewriteTrivia As Func(Of InternalSyntax.SyntaxTrivia, InternalSyntax.SyntaxTrivia) = Nothing) Me._rewriteNode = rewriteNode Me._rewriteToken = rewriteToken Me._rewriteTrivia = rewriteTrivia End Sub Public Overrides Function Visit(node As InternalSyntax.VisualBasicSyntaxNode) As InternalSyntax.VisualBasicSyntaxNode Dim visited As InternalSyntax.VisualBasicSyntaxNode = MyBase.Visit(node) If _rewriteNode Is Nothing OrElse visited Is Nothing Then Return visited Else Return _rewriteNode(visited) End If End Function Public Overrides Function VisitSyntaxToken(token As InternalSyntax.SyntaxToken) As InternalSyntax.SyntaxToken Dim visited = MyBase.VisitSyntaxToken(token) If _rewriteToken Is Nothing Then Return visited Else Return _rewriteToken(visited) End If End Function Public Overrides Function VisitSyntaxTrivia(trivia As InternalSyntax.SyntaxTrivia) As InternalSyntax.SyntaxTrivia Dim visited As InternalSyntax.SyntaxTrivia = MyBase.VisitSyntaxTrivia(trivia) If _rewriteTrivia Is Nothing Then Return visited Else Return _rewriteTrivia(visited) End If End Function End Class ''' <summary> ''' This Rewriter exposes delegates for the methods that would normally be overridden. ''' </summary> Friend Class RedRewriter Inherits VisualBasicSyntaxRewriter Private ReadOnly _rewriteNode As Func(Of SyntaxNode, SyntaxNode) Private ReadOnly _rewriteToken As Func(Of SyntaxToken, SyntaxToken) Private ReadOnly _rewriteTrivia As Func(Of SyntaxTrivia, SyntaxTrivia) Friend Sub New( Optional rewriteNode As Func(Of SyntaxNode, SyntaxNode) = Nothing, Optional rewriteToken As Func(Of SyntaxToken, SyntaxToken) = Nothing, Optional rewriteTrivia As Func(Of SyntaxTrivia, SyntaxTrivia) = Nothing) Me._rewriteNode = rewriteNode Me._rewriteToken = rewriteToken Me._rewriteTrivia = rewriteTrivia End Sub Public Overrides Function Visit(node As SyntaxNode) As SyntaxNode Dim visited = MyBase.Visit(node) If _rewriteNode Is Nothing OrElse visited Is Nothing Then Return visited Else Return _rewriteNode(visited) End If End Function Public Overrides Function VisitToken(token As SyntaxToken) As SyntaxToken Dim visited As SyntaxToken = MyBase.VisitToken(token) If _rewriteToken Is Nothing Then Return visited Else Return _rewriteToken(visited) End If End Function Public Overrides Function VisitTrivia(trivia As SyntaxTrivia) As SyntaxTrivia Dim visited As SyntaxTrivia = MyBase.VisitTrivia(trivia) If _rewriteTrivia Is Nothing Then Return visited Else Return _rewriteTrivia(visited) End If End Function End Class #End Region ' Helper Types 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.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SyntaxRewriterTests #Region "Green Tree / SeparatedSyntaxList" <Fact> Public Sub TestGreenSeparatedDeleteNone() ' the argument list Is a SeparatedSyntaxList Dim input = "F(A,B,C)" Dim output = input Dim rewriter = New GreenRewriter() TestGreen(input, output, rewriter, isStmt:=True) End Sub <Fact> Public Sub TestGreenSeparatedDeleteSome() ' the argument list Is a SeparatedSyntaxList Dim input = "F(A,B,C)" Dim output = "F(A,C)" ' delete the middle argument (should clear the following comma) Dim rewriter = New GreenRewriter(rewriteNode:= Function(node) Return If(node.Kind = SyntaxKind.SimpleArgument AndAlso node.ToString() = "B", Nothing, node) End Function) TestGreen(input, output, rewriter, isStmt:=True) End Sub <Fact> Public Sub TestGreenSeparatedDeleteAll() ' the argument list Is a SeparatedSyntaxList Dim input = "F(A,B,C)" Dim output = "F()" ' delete all arguments, should clear the intervening commas Dim rewriter = New GreenRewriter(rewriteNode:= Function(node) Return If(node.Kind = SyntaxKind.SimpleArgument, Nothing, node) End Function) TestGreen(input, output, rewriter, isStmt:=True) End Sub #End Region ' Green Tree / SeparatedSyntaxList #Region "Green Tree / SyntaxList" <Fact> Public Sub TestGreenDeleteNone() ' class declarations constitute a SyntaxList Dim input = <![CDATA[ Class A End Class Class B End Class Class C End Class ]]>.Value Dim output = input Dim rewriter As GreenRewriter = New GreenRewriter() TestGreen(input, output, rewriter, isStmt:=False) End Sub <Fact> Public Sub TestGreenDeleteSome() ' class declarations constitute a SyntaxList Dim input = <![CDATA[ Class A End Class Class B End Class Class C End Class ]]>.Value Dim output = <![CDATA[ Class A End Class Class C End Class ]]>.Value Dim rewriter = New GreenRewriter(rewriteNode:= Function(node) Return If(node.Kind = SyntaxKind.ClassBlock AndAlso node.ToString().Contains("B"), Nothing, node) End Function) TestGreen(input, output, rewriter, isStmt:=False) End Sub <Fact> Public Sub TestGreenDeleteAll() ' class declarations constitute a SyntaxList Dim input = <![CDATA[ Class A End Class Class B End Class Class C End Class ]]>.Value Dim output = <![CDATA[ ]]>.Value ' delete all statements Dim rewriter = New GreenRewriter(rewriteNode:= Function(node) Return If(node.Kind = SyntaxKind.ClassBlock, Nothing, node) End Function) TestGreen(input, output, rewriter, isStmt:=False) End Sub #End Region ' Green Tree / SyntaxList #Region "Red Tree / SeparatedSyntaxList" <Fact> Public Sub TestRedSeparatedDeleteNone() ' the argument list Is a SeparatedSyntaxList Dim input = "F(A,B,C)" Dim output = input Dim rewriter = New RedRewriter() TestRed(input, output, rewriter, isStmt:=True) End Sub <Fact> Public Sub TestRedSeparatedDeleteSome() ' the argument list Is a SeparatedSyntaxList Dim input = "F(A,B,C)" ' delete the middle type argument (should clear the following comma) Dim rewriter = New RedRewriter(rewriteNode:= Function(node) Return If(node.Kind = SyntaxKind.SimpleArgument AndAlso node.ToString() = "B", Nothing, node) End Function) Dim caught As Exception = Nothing Try TestRed(input, "", rewriter, isStmt:=True) Catch ex As InvalidOperationException caught = ex End Try Assert.NotNull(caught) End Sub <Fact> Public Sub TestRedSeparatedDeleteAll() ' the argument list Is a SeparatedSyntaxList Dim input = "F(A,B,C)" ' delete all arguments, should clear the intervening commas Dim rewriter = New RedRewriter(rewriteNode:= Function(node) Return If(node.Kind = SyntaxKind.SimpleArgument, Nothing, node) End Function) Dim caught As Exception = Nothing Try TestRed(input, "", rewriter, isStmt:=True) Catch ex As InvalidOperationException caught = ex End Try Assert.NotNull(caught) End Sub #End Region ' Red Tree / SeparatedSyntaxList #Region "Red Tree / SyntaxTokenList" <Fact> Public Sub TestRedTokenDeleteNone() ' commas in an implicit array creation constitute a SyntaxTokenList Dim input = <![CDATA[ Class c Sub s(x as Boolean(,,)) End Sub End Class ]]>.Value Dim output = input Dim rewriter As RedRewriter = New RedRewriter() TestRed(input, output, rewriter, isStmt:=False) End Sub <Fact> Public Sub TestRedTokenDeleteSome() ' commas in an implicit array creation constitute a SyntaxTokenList Dim input = <![CDATA[ Class c Sub s(x as Boolean(,,)) End Sub End Class ]]>.Value Dim output = <![CDATA[ Class c Sub s(x as Boolean(,)) End Sub End Class ]]>.Value ' delete one comma Dim first As Boolean = True Dim rewriter = New RedRewriter(rewriteToken:= Function(token) If token.Kind = SyntaxKind.CommaToken AndAlso first Then first = False Return Nothing End If Return token End Function) TestRed(input, output, rewriter, isStmt:=False) End Sub <Fact> Public Sub TestRedTokenDeleteAll() ' commas in an implicit array creation constitute a SyntaxTokenList Dim input = <![CDATA[ Class c Sub s(x as Boolean(,,)) End Sub End Class ]]>.Value Dim output = <![CDATA[ Class c Sub s(x as Boolean()) End Sub End Class ]]>.Value ' delete all commas Dim rewriter = New RedRewriter(rewriteToken:= Function(token) Return If(token.Kind = SyntaxKind.CommaToken, Nothing, token) End Function) TestRed(input, output, rewriter, isStmt:=False) End Sub #End Region ' Red Tree / SyntaxTokenList #Region "Red Tree / SyntaxNodeOrTokenList" ' These only in the syntax tree inside SeparatedSyntaxLists, so they are not visitable. ' We can't call this directly due to its protection level. #End Region ' Red Tree / SyntaxNodeOrTokenList #Region "Red Tree / SyntaxTriviaList" <Fact> Public Sub TestRedTriviaDeleteNone() ' whitespace and comments constitute a SyntaxTriviaList Dim input = " a() ' comment" Dim output = input Dim rewriter As RedRewriter = New RedRewriter() TestRed(input, output, rewriter, isStmt:=True) End Sub <Fact> Public Sub TestRedTriviaDeleteSome() ' whitespace and comments constitute a SyntaxTriviaList Dim input = " a() ' comment" Dim output = "a()' comment" ' delete all whitespace trivia (leave comments) Dim rewriter = New RedRewriter(rewriteTrivia:= Function(trivia) Return If(trivia.Kind = SyntaxKind.WhitespaceTrivia, Nothing, trivia) End Function) TestRed(input, output, rewriter, isStmt:=True) End Sub <Fact> Public Sub TestRedTriviaDeleteAll() ' whitespace and comments constitute a SyntaxTriviaList Dim input = " a() ' comment" Dim output = "a()" ' delete all trivia Dim rewriter = New RedRewriter(rewriteTrivia:=Function(trivia) Nothing) TestRed(input, output, rewriter, isStmt:=True) End Sub #End Region ' Red Tree / SyntaxTriviaList #Region "Red Tree / SyntaxList" <Fact> Public Sub TestRedDeleteNone() ' attributes are a SyntaxList Dim input = <![CDATA[ <Attr1()> <Attr2()> <Attr3()> Class Q End Class ]]>.Value Dim output = input Dim rewriter = New RedRewriter() TestRed(input, output, rewriter, isStmt:=False) End Sub <Fact> Public Sub TestRedDeleteSome() ' attributes are a SyntaxList Dim input = <![CDATA[ <Attr1()> <Attr2()> <Attr3()> Class Q End Class ]]>.Value Dim output = <![CDATA[ <Attr1()> <Attr3()> Class Q End Class ]]>.Value Dim rewriter = New RedRewriter(rewriteNode:= Function(node) Return If(node.Kind = SyntaxKind.AttributeList AndAlso node.ToString().Contains("2"), Nothing, node) End Function) TestRed(input, output, rewriter, isStmt:=False) End Sub <Fact> Public Sub TestRedDeleteAll() ' attributes are a SyntaxList Dim input = <![CDATA[ <Attr1()> <Attr2()> <Attr3()> Class Q End Class ]]>.Value Dim output = <![CDATA[ Class Q End Class ]]>.Value Dim rewriter = New RedRewriter(rewriteNode:= Function(node) Return If(node.Kind = SyntaxKind.AttributeList, Nothing, node) End Function) TestRed(input, output, rewriter, isStmt:=False) End Sub #End Region ' Red Tree / SyntaxList #Region "Misc" <Fact> Public Sub TestRedSeparatedDeleteLast() Dim input = "F(A,B,C)" Dim output = "F(A,B,)" ' delete the last argument (should clear the *preceding* comma) Dim rewriter = New RedRewriter(rewriteNode:= Function(node) Return If(node.Kind = SyntaxKind.SimpleArgument AndAlso node.ToString() = "C", Nothing, node) End Function) TestRed(input, output, rewriter, isStmt:=True) End Sub <Fact> Public Sub TestGreenSeparatedDeleteLast() Dim input = "F(A,B,C)" Dim output = "F(A,B)" ' delete the last argument (should clear the *preceding* comma) Dim rewriter = New GreenRewriter(rewriteNode:= Function(node) Return If(node.Kind = SyntaxKind.SimpleArgument AndAlso node.ToString() = "C", Nothing, node) End Function) TestGreen(input, output, rewriter, isStmt:=True) End Sub <Fact> Public Sub TestRedSeparatedDeleteLastWithTrailingSeparator() Dim input = <![CDATA[ Class Q Sub A() End Sub Sub B() End Sub End Class ]]>.Value Dim rewriter = New RedRewriter(rewriteNode:= Function(node) Return If(node.Kind = SyntaxKind.SubBlock AndAlso node.ToString().Contains("B"), Nothing, node) End Function) Dim caught As Exception = Nothing Dim output = <![CDATA[ Class Q Sub A() End Sub End Class ]]>.Value TestRed(input, output, rewriter, isStmt:=False) End Sub <Fact> Public Sub TestGreenSeparatedDeleteLastWithTrailingSeparator() Dim input = <![CDATA[ Class Q Sub A() End Sub Sub B() End Sub End Class ]]>.Value Dim output = <![CDATA[ Class Q Sub A() End Sub End Class ]]>.Value Dim rewriter = New GreenRewriter(rewriteNode:= Function(node) Return If(node.Kind = SyntaxKind.SubBlock AndAlso node.ToString().Contains("B"), Nothing, node) End Function) TestGreen(input, output, rewriter, isStmt:=False) End Sub <Fact> Public Sub TestRedSeparatedDeleteSeparator() Dim red = SyntaxFactory.ParseExecutableStatement("F(A,B,C)") Assert.False(red.ContainsDiagnostics) Dim rewriter = New RedRewriter(rewriteToken:= Function(token) Return If(token.Kind = SyntaxKind.CommaToken, Nothing, token) End Function) Assert.Throws(Of InvalidOperationException)(Sub() rewriter.Visit(red)) End Sub <Fact> Public Sub TestCreateSyntaxTreeWithoutClone() ' Test SyntaxTree.CreateWithoutClone() implicitly invoked by accessing the SyntaxTree property. ' Ensure this API preserves reference equality of the syntax node. Dim expression = SyntaxFactory.ParseExpression("0") Dim tree = expression.SyntaxTree Assert.Same(expression, tree.GetRoot()) Assert.False(tree.HasCompilationUnitRoot, "how did we get a CompilationUnit root?") End Sub <Fact> Public Sub RemoveDocCommentNode() Dim oldSource = <![CDATA[ ''' <see cref='C'/> Class C End Class ]]> Dim expectedNewSource = <![CDATA[ ''' Class C End Class ]]> Dim oldTree = VisualBasicSyntaxTree.ParseText(oldSource.Value, options:=New VisualBasicParseOptions(documentationMode:=DocumentationMode.Diagnose)) Dim oldRoot = oldTree.GetRoot() Dim xmlNode = oldRoot.DescendantNodes(descendIntoTrivia:=True).OfType(Of XmlEmptyElementSyntax)().Single() Dim newRoot = oldRoot.RemoveNode(xmlNode, SyntaxRemoveOptions.KeepDirectives) Assert.Equal(expectedNewSource.Value, newRoot.ToFullString()) End Sub <WorkItem(991474, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991474")> <Fact> Public Sub ReturnNothingFromStructuredTriviaRoot_Succeeds() Dim Text = <x>#Region Class C End Class #End Region"</x>.Value Dim expectedText = <x>Class C End Class #End Region"</x>.Value Dim root = SyntaxFactory.ParseCompilationUnit(Text) Dim newRoot = New RemoveRegionRewriter().Visit(root) Assert.Equal(expectedText, newRoot.ToFullString()) End Sub <Fact> <WorkItem(22010, "https://github.com/dotnet/roslyn/issues/22010")> Public Sub TestReplaceNodeShouldNotLoseParseOptions() Dim tree = SyntaxFactory.ParseSyntaxTree("System.Console.Write(""Before"")", TestOptions.Script) Assert.Equal(SourceCodeKind.Script, tree.Options.Kind) Dim root = tree.GetRoot() Dim before = root.DescendantNodes().OfType(Of LiteralExpressionSyntax)().Single() Dim after = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal("After")) Dim newRoot = root.ReplaceNode(before, after) Dim newTree = newRoot.SyntaxTree Assert.Equal(SourceCodeKind.Script, newTree.Options.Kind) Assert.Equal(tree.Options, newTree.Options) End Sub <Fact> <WorkItem(22010, "https://github.com/dotnet/roslyn/issues/22010")> Public Sub TestReplaceNodeInListShouldNotLoseParseOptions() Dim tree = SyntaxFactory.ParseSyntaxTree("m(a, b)", TestOptions.Script) Assert.Equal(SourceCodeKind.Script, tree.Options.Kind) Dim argC = SyntaxFactory.SimpleArgument(SyntaxFactory.ParseExpression("c")) Dim argD = SyntaxFactory.SimpleArgument(SyntaxFactory.ParseExpression("d")) Dim root = tree.GetRoot() Dim invocation = root.DescendantNodes().OfType(Of InvocationExpressionSyntax)().Single() Dim newRoot = root.ReplaceNode(invocation.ArgumentList.Arguments(0), New SyntaxNode() {argC, argD}) Assert.Equal("m(c,d, b)", newRoot.ToFullString()) Dim newTree = newRoot.SyntaxTree Assert.Equal(SourceCodeKind.Script, newTree.Options.Kind) Assert.Equal(tree.Options, newTree.Options) End Sub <Fact> <WorkItem(22010, "https://github.com/dotnet/roslyn/issues/22010")> Public Sub TestInsertNodeShouldNotLoseParseOptions() Dim tree = SyntaxFactory.ParseSyntaxTree("m(a, b)", TestOptions.Script) Assert.Equal(SourceCodeKind.Script, tree.Options.Kind) Dim argC = SyntaxFactory.SimpleArgument(SyntaxFactory.ParseExpression("c")) Dim argD = SyntaxFactory.SimpleArgument(SyntaxFactory.ParseExpression("d")) Dim root = tree.GetRoot() Dim invocation = root.DescendantNodes().OfType(Of InvocationExpressionSyntax)().Single() ' insert before first Dim newNode = invocation.InsertNodesBefore(invocation.ArgumentList.Arguments(0), New SyntaxNode() {argC, argD}) Assert.Equal("m(c,d,a, b)", newNode.ToFullString()) Dim newTree = newNode.SyntaxTree Assert.Equal(SourceCodeKind.Script, newTree.Options.Kind) Assert.Equal(tree.Options, newTree.Options) ' insert after first Dim newNode2 = invocation.InsertNodesAfter(invocation.ArgumentList.Arguments(0), New SyntaxNode() {argC, argD}) Assert.Equal("m(a,c,d, b)", newNode2.ToFullString()) Dim newTree2 = newNode2.SyntaxTree Assert.Equal(SourceCodeKind.Script, newTree2.Options.Kind) Assert.Equal(tree.Options, newTree2.Options) End Sub <Fact> <WorkItem(22010, "https://github.com/dotnet/roslyn/issues/22010")> Public Sub TestReplaceTokenShouldNotLoseParseOptions() Dim tree = SyntaxFactory.ParseSyntaxTree("Private Class C ", options:=TestOptions.Script) Assert.Equal(SourceCodeKind.Script, tree.Options.Kind) Dim root = tree.GetRoot() Dim privateToken = root.DescendantTokens().First() Dim publicToken = SyntaxFactory.ParseToken("Public ") Dim partialToken = SyntaxFactory.ParseToken("Partial ") Dim newRoot = root.ReplaceToken(privateToken, New SyntaxToken() {publicToken, partialToken}) Assert.Equal("Public Partial Class C ", newRoot.ToFullString()) Dim newTree = newRoot.SyntaxTree Assert.Equal(SourceCodeKind.Script, newTree.Options.Kind) Assert.Equal(tree.Options, newTree.Options) End Sub <Fact> <WorkItem(22010, "https://github.com/dotnet/roslyn/issues/22010")> Public Sub TestInsertTokenShouldNotLoseParseOptions() Dim tree = SyntaxFactory.ParseSyntaxTree("Public Class C" & vbCrLf & "End Class", options:=TestOptions.Script) Dim root = tree.GetRoot() Dim publicToken = root.DescendantTokens().First() Dim partialToken = SyntaxFactory.ParseToken("Partial ") Dim staticToken = SyntaxFactory.ParseToken("Shared ") Dim newRoot = root.InsertTokensBefore(publicToken, New SyntaxToken() {staticToken}) Assert.Equal("Shared Public Class C" & vbCrLf & "End Class", newRoot.ToFullString()) Dim newTree = newRoot.SyntaxTree Assert.Equal(SourceCodeKind.Script, newTree.Options.Kind) Assert.Equal(tree.Options, newTree.Options) Dim newRoot2 = root.InsertTokensAfter(publicToken, New SyntaxToken() {staticToken}) Assert.Equal("Public Shared Class C" & vbCrLf & "End Class", newRoot2.ToFullString()) Dim newTree2 = newRoot2.SyntaxTree Assert.Equal(SourceCodeKind.Script, newTree2.Options.Kind) Assert.Equal(tree.Options, newTree2.Options) End Sub <Fact> <WorkItem(22010, "https://github.com/dotnet/roslyn/issues/22010")> Public Sub TestReplaceTriviaShouldNotLoseParseOptions() Dim tree = SyntaxFactory.ParseSyntaxTree("Dim identifier 'c", options:=TestOptions.Script) Dim field = tree.GetRoot().DescendantNodes().OfType(Of FieldDeclarationSyntax).Single() Dim trailingTrivia = field.GetTrailingTrivia() Assert.Equal(2, trailingTrivia.Count) Dim comment1 = trailingTrivia(1) Assert.Equal(SyntaxKind.CommentTrivia, comment1.Kind()) Dim newComment1 = SyntaxFactory.ParseLeadingTrivia("'a")(0) Dim newComment2 = SyntaxFactory.ParseLeadingTrivia("'b")(0) Dim newField = field.ReplaceTrivia(comment1, New SyntaxTrivia() {newComment1, newComment2}) Assert.Equal("Dim identifier 'a'b", newField.ToFullString()) Dim newTree = newField.SyntaxTree Assert.Equal(SourceCodeKind.Script, newTree.Options.Kind) Assert.Equal(tree.Options, newTree.Options) Dim newRoot2 = field.ReplaceTrivia(comment1, New SyntaxTrivia() {}) Assert.Equal("Dim identifier ", newRoot2.ToFullString()) Dim newTree2 = newRoot2.SyntaxTree Assert.Equal(SourceCodeKind.Script, newTree2.Options.Kind) Assert.Equal(tree.Options, newTree2.Options) End Sub <Fact> <WorkItem(22010, "https://github.com/dotnet/roslyn/issues/22010")> Public Sub TestInsertTriviaShouldNotLoseParseOptions() Dim tree = SyntaxFactory.ParseSyntaxTree("Dim identifier 'c", options:=TestOptions.Script) Dim field = tree.GetRoot().DescendantNodes().OfType(Of FieldDeclarationSyntax).Single() Dim trailingTrivia = field.GetTrailingTrivia() Assert.Equal(2, trailingTrivia.Count) Dim comment1 = trailingTrivia(1) Assert.Equal(SyntaxKind.CommentTrivia, comment1.Kind()) Dim newComment1 = SyntaxFactory.ParseLeadingTrivia("'a")(0) Dim newComment2 = SyntaxFactory.ParseLeadingTrivia("'b")(0) Dim newField = field.InsertTriviaAfter(comment1, New SyntaxTrivia() {newComment1, newComment2}) Assert.Equal("Dim identifier 'c'a'b", newField.ToFullString()) Dim newTree = newField.SyntaxTree Assert.Equal(SourceCodeKind.Script, newTree.Options.Kind) Assert.Equal(tree.Options, newTree.Options) End Sub <Fact> <WorkItem(22010, "https://github.com/dotnet/roslyn/issues/22010")> Public Sub TestRemoveNodeShouldNotLoseParseOptions() Dim tree = SyntaxFactory.ParseSyntaxTree("Private Class C" & vbCrLf & "End Class", options:=TestOptions.Script) Dim root = tree.GetRoot() Dim newRoot = root.RemoveNode(root.DescendantNodes().First(), SyntaxRemoveOptions.KeepDirectives) Dim newTree = newRoot.SyntaxTree Assert.Equal(SourceCodeKind.Script, newTree.Options.Kind) Assert.Equal(tree.Options, newTree.Options) End Sub <Fact> <WorkItem(22010, "https://github.com/dotnet/roslyn/issues/22010")> Public Sub TestNormalizeWhitespaceShouldNotLoseParseOptions() Dim tree = SyntaxFactory.ParseSyntaxTree("Private Class C" & vbCrLf & "End Class", options:=TestOptions.Script) Dim root = tree.GetRoot() Dim newRoot = root.NormalizeWhitespace(" ") Dim newTree = newRoot.SyntaxTree Assert.Equal(SourceCodeKind.Script, newTree.Options.Kind) Assert.Equal(tree.Options, newTree.Options) End Sub Private Class RemoveRegionRewriter Inherits VisualBasicSyntaxRewriter Public Sub New() MyBase.New(visitIntoStructuredTrivia:=True) End Sub Public Overrides Function VisitRegionDirectiveTrivia(node As RegionDirectiveTriviaSyntax) As SyntaxNode Return Nothing End Function End Class #End Region ' Misc #Region "Helper Types" Private Sub TestGreen(input As String, output As String, rewriter As GreenRewriter, isStmt As Boolean) Dim red As VisualBasicSyntaxNode If isStmt Then red = SyntaxFactory.ParseExecutableStatement(input) Else red = SyntaxFactory.ParseCompilationUnit(input) End If Dim green = red.ToGreen() Assert.False(green.ContainsDiagnostics) Dim result As InternalSyntax.VisualBasicSyntaxNode = rewriter.Visit(green) Assert.Equal(input = output, green Is result) Assert.Equal(output.Trim(), result.ToFullString().Trim()) End Sub Private Sub TestRed(input As String, output As String, rewriter As RedRewriter, isStmt As Boolean) Dim red As VisualBasicSyntaxNode If isStmt Then red = SyntaxFactory.ParseExecutableStatement(input) Else red = SyntaxFactory.ParseCompilationUnit(input) End If Assert.False(red.ContainsDiagnostics) Dim result = rewriter.Visit(red) Assert.Equal(input = output, red Is result) Assert.Equal(output.Trim(), result.ToFullString().Trim()) End Sub #End Region ' Helper Types #Region "Helper Types" ''' <summary> ''' This Rewriter exposes delegates for the methods that would normally be overridden. ''' </summary> Friend Class GreenRewriter Inherits InternalSyntax.VisualBasicSyntaxRewriter Private ReadOnly _rewriteNode As Func(Of InternalSyntax.VisualBasicSyntaxNode, InternalSyntax.VisualBasicSyntaxNode) Private ReadOnly _rewriteToken As Func(Of InternalSyntax.SyntaxToken, InternalSyntax.SyntaxToken) Private ReadOnly _rewriteTrivia As Func(Of InternalSyntax.SyntaxTrivia, InternalSyntax.SyntaxTrivia) Friend Sub New( Optional rewriteNode As Func(Of InternalSyntax.VisualBasicSyntaxNode, InternalSyntax.VisualBasicSyntaxNode) = Nothing, Optional rewriteToken As Func(Of InternalSyntax.SyntaxToken, InternalSyntax.SyntaxToken) = Nothing, Optional rewriteTrivia As Func(Of InternalSyntax.SyntaxTrivia, InternalSyntax.SyntaxTrivia) = Nothing) Me._rewriteNode = rewriteNode Me._rewriteToken = rewriteToken Me._rewriteTrivia = rewriteTrivia End Sub Public Overrides Function Visit(node As InternalSyntax.VisualBasicSyntaxNode) As InternalSyntax.VisualBasicSyntaxNode Dim visited As InternalSyntax.VisualBasicSyntaxNode = MyBase.Visit(node) If _rewriteNode Is Nothing OrElse visited Is Nothing Then Return visited Else Return _rewriteNode(visited) End If End Function Public Overrides Function VisitSyntaxToken(token As InternalSyntax.SyntaxToken) As InternalSyntax.SyntaxToken Dim visited = MyBase.VisitSyntaxToken(token) If _rewriteToken Is Nothing Then Return visited Else Return _rewriteToken(visited) End If End Function Public Overrides Function VisitSyntaxTrivia(trivia As InternalSyntax.SyntaxTrivia) As InternalSyntax.SyntaxTrivia Dim visited As InternalSyntax.SyntaxTrivia = MyBase.VisitSyntaxTrivia(trivia) If _rewriteTrivia Is Nothing Then Return visited Else Return _rewriteTrivia(visited) End If End Function End Class ''' <summary> ''' This Rewriter exposes delegates for the methods that would normally be overridden. ''' </summary> Friend Class RedRewriter Inherits VisualBasicSyntaxRewriter Private ReadOnly _rewriteNode As Func(Of SyntaxNode, SyntaxNode) Private ReadOnly _rewriteToken As Func(Of SyntaxToken, SyntaxToken) Private ReadOnly _rewriteTrivia As Func(Of SyntaxTrivia, SyntaxTrivia) Friend Sub New( Optional rewriteNode As Func(Of SyntaxNode, SyntaxNode) = Nothing, Optional rewriteToken As Func(Of SyntaxToken, SyntaxToken) = Nothing, Optional rewriteTrivia As Func(Of SyntaxTrivia, SyntaxTrivia) = Nothing) Me._rewriteNode = rewriteNode Me._rewriteToken = rewriteToken Me._rewriteTrivia = rewriteTrivia End Sub Public Overrides Function Visit(node As SyntaxNode) As SyntaxNode Dim visited = MyBase.Visit(node) If _rewriteNode Is Nothing OrElse visited Is Nothing Then Return visited Else Return _rewriteNode(visited) End If End Function Public Overrides Function VisitToken(token As SyntaxToken) As SyntaxToken Dim visited As SyntaxToken = MyBase.VisitToken(token) If _rewriteToken Is Nothing Then Return visited Else Return _rewriteToken(visited) End If End Function Public Overrides Function VisitTrivia(trivia As SyntaxTrivia) As SyntaxTrivia Dim visited As SyntaxTrivia = MyBase.VisitTrivia(trivia) If _rewriteTrivia Is Nothing Then Return visited Else Return _rewriteTrivia(visited) End If End Function End Class #End Region ' Helper Types End Class End Namespace
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/ExpressionEvaluator/CSharp/Test/ResultProvider/ObjectFavoritesTests.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.Globalization; using System.Linq; using DiffPlex.Model; using Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Symbols; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class ObjectFavoritesTests : CSharpResultProviderTestBase { [Fact] public void Expansion() { var source = @"class A { string s1 = ""S1""; string s2 = ""S2""; } class B : A { string s3 = ""S3""; string s4 = ""S4""; } class C { A a = new A(); B b = new B(); }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var rootExpr = "new C()"; var favoritesByTypeName = new Dictionary<string, DkmClrObjectFavoritesInfo>() { { "C", new DkmClrObjectFavoritesInfo(new[] { "b" }) }, { "B", new DkmClrObjectFavoritesInfo(new[] { "s4", "s2" }) } }; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(assembly), favoritesByTypeName); var value = CreateDkmClrValue( value: Activator.CreateInstance(type), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.HasFavorites)); var children = GetChildren(evalResult); Verify(children, EvalResult("b", "{B}", "B", "(new C()).b", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite | DkmEvaluationResultFlags.IsFavorite | DkmEvaluationResultFlags.HasFavorites), EvalResult("a", "{A}", "A", "(new C()).a", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite)); // B b = new B(); var more = GetChildren(children[0]); Verify(more, EvalResult("s4", @"""S4""", "string", "(new C()).b.s4", DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.CanFavorite | DkmEvaluationResultFlags.IsFavorite, editableValue: @"""S4"""), EvalResult("s2", @"""S2""", "string", "(new C()).b.s2", DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.CanFavorite | DkmEvaluationResultFlags.IsFavorite, editableValue: @"""S2"""), EvalResult("s1", @"""S1""", "string", "(new C()).b.s1", DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.CanFavorite, editableValue: @"""S1"""), EvalResult("s3", @"""S3""", "string", "(new C()).b.s3", DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.CanFavorite, editableValue: @"""S3""")); // A a = new A(); more = GetChildren(children[1]); Verify(more, EvalResult("s1", @"""S1""", "string", "(new C()).a.s1", DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.CanFavorite, editableValue: @"""S1"""), EvalResult("s2", @"""S2""", "string", "(new C()).a.s2", DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.CanFavorite, editableValue: @"""S2""")); } [Fact] public void ExpansionOfNullValue() { var source = @"class A { string s1 = ""S1""; string s2 = ""S2""; } class B { A a1 = new A(); A a2 = null; }"; var assembly = GetAssembly(source); var type = assembly.GetType("B"); var rootExpr = "new B()"; var favoritesByTypeName = new Dictionary<string, DkmClrObjectFavoritesInfo>() { { "A", new DkmClrObjectFavoritesInfo(new[] { "s2" }) } }; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(assembly), favoritesByTypeName); var value = CreateDkmClrValue( value: Activator.CreateInstance(type), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{B}", "B", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("a1", "{A}", "A", "(new B()).a1", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite | DkmEvaluationResultFlags.HasFavorites), EvalResult("a2", "null", "A", "(new B()).a2", DkmEvaluationResultFlags.CanFavorite)); // A a1 = new A(); var more = GetChildren(children[0]); Verify(more, EvalResult("s2", @"""S2""", "string", "(new B()).a1.s2", DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.CanFavorite | DkmEvaluationResultFlags.IsFavorite, editableValue: @"""S2"""), EvalResult("s1", @"""S1""", "string", "(new B()).a1.s1", DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.CanFavorite, editableValue: @"""S1""")); } [Fact] public void FilteredExpansion() { var source = @"class A { string s1 = ""S1""; string s2 = ""S2""; } class B : A { string s3 = ""S3""; string s4 = ""S4""; } class C { A a = new A(); B b = new B(); }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var rootExpr = "new C()"; var favoritesByTypeName = new Dictionary<string, DkmClrObjectFavoritesInfo>() { { "C", new DkmClrObjectFavoritesInfo(new[] { "b" }) }, { "B", new DkmClrObjectFavoritesInfo(new[] { "s4", "s2" }) } }; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(assembly), favoritesByTypeName); var value = CreateDkmClrValue( value: Activator.CreateInstance(type), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult(rootExpr, value, null, CreateDkmInspectionContext(DkmEvaluationFlags.FilterToFavorites)); Verify(evalResult, EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.HasFavorites)); var children = GetChildren(evalResult, CreateDkmInspectionContext(DkmEvaluationFlags.FilterToFavorites)); Verify(children, EvalResult("b", "{B}", "B", "(new C()).b", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite | DkmEvaluationResultFlags.IsFavorite | DkmEvaluationResultFlags.HasFavorites)); // B b = new B(); var more = GetChildren(children[0], CreateDkmInspectionContext(DkmEvaluationFlags.FilterToFavorites)); Verify(more, EvalResult("s4", @"""S4""", "string", "(new C()).b.s4", DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.CanFavorite | DkmEvaluationResultFlags.IsFavorite, editableValue: @"""S4"""), EvalResult("s2", @"""S2""", "string", "(new C()).b.s2", DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.CanFavorite | DkmEvaluationResultFlags.IsFavorite, editableValue: @"""S2""")); } [Fact] public void DisplayString() { var source = @"class A { string s1 = ""S1""; string s2 = ""S2""; string s3 = ""S3""; string s4 = ""S4""; }"; var assembly = GetAssembly(source); var type = assembly.GetType("A"); var rootExpr = "new A()"; var favoritesByTypeName = new Dictionary<string, DkmClrObjectFavoritesInfo>() { { "A", new DkmClrObjectFavoritesInfo(new[] { "s4", "s2" }, "s4 = {s4}, s2 = {s2}") } }; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(assembly), favoritesByTypeName); var value = CreateDkmClrValue( value: Activator.CreateInstance(type), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, @"s4 = ""S4"", s2 = ""S2""", "A", rootExpr, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.HasFavorites)); } [Fact] public void SimpleDisplayString() { var source = @"class A { string s1 = ""S1""; string s2 = ""S2""; string s3 = ""S3""; string s4 = ""S4""; }"; var assembly = GetAssembly(source); var type = assembly.GetType("A"); var rootExpr = "new A()"; var favoritesByTypeName = new Dictionary<string, DkmClrObjectFavoritesInfo>() { { "A", new DkmClrObjectFavoritesInfo(new[] { "s4", "s2" }, "s4 = {s4}, s2 = {s2}", "{s4}, {s2}") } }; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(assembly), favoritesByTypeName); var value = CreateDkmClrValue( value: Activator.CreateInstance(type), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult(rootExpr, value, null, CreateDkmInspectionContext(DkmEvaluationFlags.UseSimpleDisplayString)); Verify(evalResult, EvalResult(rootExpr, @"""S4"", ""S2""", "A", rootExpr, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.HasFavorites)); } [Fact] public void Nullable() { var source = @"struct A { public string s1; public string s2; public A(string s1, string s2) { this.s1 = s1; this.s2 = s2; } } class B { A? a1 = null; A? a2 = new A(""S1"", ""S2""); }"; var assembly = GetAssembly(source); var type = assembly.GetType("B"); var rootExpr = "new B()"; var favoritesByTypeName = new Dictionary<string, DkmClrObjectFavoritesInfo>() { { "B", new DkmClrObjectFavoritesInfo(new[] { "a2" }) }, { "A", new DkmClrObjectFavoritesInfo(new[] { "s2" }) } }; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(assembly), favoritesByTypeName); var value = CreateDkmClrValue( value: Activator.CreateInstance(type), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{B}", "B", rootExpr, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.HasFavorites)); var children = GetChildren(evalResult); Verify(children, EvalResult("a2", "{A}", "A?", "(new B()).a2", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite | DkmEvaluationResultFlags.IsFavorite | DkmEvaluationResultFlags.HasFavorites), EvalResult("a1", "null", "A?", "(new B()).a1", DkmEvaluationResultFlags.CanFavorite)); // A? a2 = new A(); var more = GetChildren(children[0]); Verify(more, EvalResult("s2", @"""S2""", "string", "(new B()).a2.s2", DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.CanFavorite | DkmEvaluationResultFlags.IsFavorite, editableValue: @"""S2"""), EvalResult("s1", @"""S1""", "string", "(new B()).a2.s1", DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.CanFavorite, editableValue: @"""S1""")); } } }
// Licensed to the .NET Foundation under one or more 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.Globalization; using System.Linq; using DiffPlex.Model; using Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Symbols; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class ObjectFavoritesTests : CSharpResultProviderTestBase { [Fact] public void Expansion() { var source = @"class A { string s1 = ""S1""; string s2 = ""S2""; } class B : A { string s3 = ""S3""; string s4 = ""S4""; } class C { A a = new A(); B b = new B(); }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var rootExpr = "new C()"; var favoritesByTypeName = new Dictionary<string, DkmClrObjectFavoritesInfo>() { { "C", new DkmClrObjectFavoritesInfo(new[] { "b" }) }, { "B", new DkmClrObjectFavoritesInfo(new[] { "s4", "s2" }) } }; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(assembly), favoritesByTypeName); var value = CreateDkmClrValue( value: Activator.CreateInstance(type), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.HasFavorites)); var children = GetChildren(evalResult); Verify(children, EvalResult("b", "{B}", "B", "(new C()).b", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite | DkmEvaluationResultFlags.IsFavorite | DkmEvaluationResultFlags.HasFavorites), EvalResult("a", "{A}", "A", "(new C()).a", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite)); // B b = new B(); var more = GetChildren(children[0]); Verify(more, EvalResult("s4", @"""S4""", "string", "(new C()).b.s4", DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.CanFavorite | DkmEvaluationResultFlags.IsFavorite, editableValue: @"""S4"""), EvalResult("s2", @"""S2""", "string", "(new C()).b.s2", DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.CanFavorite | DkmEvaluationResultFlags.IsFavorite, editableValue: @"""S2"""), EvalResult("s1", @"""S1""", "string", "(new C()).b.s1", DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.CanFavorite, editableValue: @"""S1"""), EvalResult("s3", @"""S3""", "string", "(new C()).b.s3", DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.CanFavorite, editableValue: @"""S3""")); // A a = new A(); more = GetChildren(children[1]); Verify(more, EvalResult("s1", @"""S1""", "string", "(new C()).a.s1", DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.CanFavorite, editableValue: @"""S1"""), EvalResult("s2", @"""S2""", "string", "(new C()).a.s2", DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.CanFavorite, editableValue: @"""S2""")); } [Fact] public void ExpansionOfNullValue() { var source = @"class A { string s1 = ""S1""; string s2 = ""S2""; } class B { A a1 = new A(); A a2 = null; }"; var assembly = GetAssembly(source); var type = assembly.GetType("B"); var rootExpr = "new B()"; var favoritesByTypeName = new Dictionary<string, DkmClrObjectFavoritesInfo>() { { "A", new DkmClrObjectFavoritesInfo(new[] { "s2" }) } }; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(assembly), favoritesByTypeName); var value = CreateDkmClrValue( value: Activator.CreateInstance(type), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{B}", "B", rootExpr, DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("a1", "{A}", "A", "(new B()).a1", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite | DkmEvaluationResultFlags.HasFavorites), EvalResult("a2", "null", "A", "(new B()).a2", DkmEvaluationResultFlags.CanFavorite)); // A a1 = new A(); var more = GetChildren(children[0]); Verify(more, EvalResult("s2", @"""S2""", "string", "(new B()).a1.s2", DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.CanFavorite | DkmEvaluationResultFlags.IsFavorite, editableValue: @"""S2"""), EvalResult("s1", @"""S1""", "string", "(new B()).a1.s1", DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.CanFavorite, editableValue: @"""S1""")); } [Fact] public void FilteredExpansion() { var source = @"class A { string s1 = ""S1""; string s2 = ""S2""; } class B : A { string s3 = ""S3""; string s4 = ""S4""; } class C { A a = new A(); B b = new B(); }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var rootExpr = "new C()"; var favoritesByTypeName = new Dictionary<string, DkmClrObjectFavoritesInfo>() { { "C", new DkmClrObjectFavoritesInfo(new[] { "b" }) }, { "B", new DkmClrObjectFavoritesInfo(new[] { "s4", "s2" }) } }; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(assembly), favoritesByTypeName); var value = CreateDkmClrValue( value: Activator.CreateInstance(type), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult(rootExpr, value, null, CreateDkmInspectionContext(DkmEvaluationFlags.FilterToFavorites)); Verify(evalResult, EvalResult(rootExpr, "{C}", "C", rootExpr, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.HasFavorites)); var children = GetChildren(evalResult, CreateDkmInspectionContext(DkmEvaluationFlags.FilterToFavorites)); Verify(children, EvalResult("b", "{B}", "B", "(new C()).b", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite | DkmEvaluationResultFlags.IsFavorite | DkmEvaluationResultFlags.HasFavorites)); // B b = new B(); var more = GetChildren(children[0], CreateDkmInspectionContext(DkmEvaluationFlags.FilterToFavorites)); Verify(more, EvalResult("s4", @"""S4""", "string", "(new C()).b.s4", DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.CanFavorite | DkmEvaluationResultFlags.IsFavorite, editableValue: @"""S4"""), EvalResult("s2", @"""S2""", "string", "(new C()).b.s2", DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.CanFavorite | DkmEvaluationResultFlags.IsFavorite, editableValue: @"""S2""")); } [Fact] public void DisplayString() { var source = @"class A { string s1 = ""S1""; string s2 = ""S2""; string s3 = ""S3""; string s4 = ""S4""; }"; var assembly = GetAssembly(source); var type = assembly.GetType("A"); var rootExpr = "new A()"; var favoritesByTypeName = new Dictionary<string, DkmClrObjectFavoritesInfo>() { { "A", new DkmClrObjectFavoritesInfo(new[] { "s4", "s2" }, "s4 = {s4}, s2 = {s2}") } }; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(assembly), favoritesByTypeName); var value = CreateDkmClrValue( value: Activator.CreateInstance(type), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, @"s4 = ""S4"", s2 = ""S2""", "A", rootExpr, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.HasFavorites)); } [Fact] public void SimpleDisplayString() { var source = @"class A { string s1 = ""S1""; string s2 = ""S2""; string s3 = ""S3""; string s4 = ""S4""; }"; var assembly = GetAssembly(source); var type = assembly.GetType("A"); var rootExpr = "new A()"; var favoritesByTypeName = new Dictionary<string, DkmClrObjectFavoritesInfo>() { { "A", new DkmClrObjectFavoritesInfo(new[] { "s4", "s2" }, "s4 = {s4}, s2 = {s2}", "{s4}, {s2}") } }; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(assembly), favoritesByTypeName); var value = CreateDkmClrValue( value: Activator.CreateInstance(type), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult(rootExpr, value, null, CreateDkmInspectionContext(DkmEvaluationFlags.UseSimpleDisplayString)); Verify(evalResult, EvalResult(rootExpr, @"""S4"", ""S2""", "A", rootExpr, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.HasFavorites)); } [Fact] public void Nullable() { var source = @"struct A { public string s1; public string s2; public A(string s1, string s2) { this.s1 = s1; this.s2 = s2; } } class B { A? a1 = null; A? a2 = new A(""S1"", ""S2""); }"; var assembly = GetAssembly(source); var type = assembly.GetType("B"); var rootExpr = "new B()"; var favoritesByTypeName = new Dictionary<string, DkmClrObjectFavoritesInfo>() { { "B", new DkmClrObjectFavoritesInfo(new[] { "a2" }) }, { "A", new DkmClrObjectFavoritesInfo(new[] { "s2" }) } }; var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(assembly), favoritesByTypeName); var value = CreateDkmClrValue( value: Activator.CreateInstance(type), type: runtime.GetType((TypeImpl)type)); var evalResult = FormatResult(rootExpr, value); Verify(evalResult, EvalResult(rootExpr, "{B}", "B", rootExpr, DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.HasFavorites)); var children = GetChildren(evalResult); Verify(children, EvalResult("a2", "{A}", "A?", "(new B()).a2", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.CanFavorite | DkmEvaluationResultFlags.IsFavorite | DkmEvaluationResultFlags.HasFavorites), EvalResult("a1", "null", "A?", "(new B()).a1", DkmEvaluationResultFlags.CanFavorite)); // A? a2 = new A(); var more = GetChildren(children[0]); Verify(more, EvalResult("s2", @"""S2""", "string", "(new B()).a2.s2", DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.CanFavorite | DkmEvaluationResultFlags.IsFavorite, editableValue: @"""S2"""), EvalResult("s1", @"""S1""", "string", "(new B()).a2.s1", DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.CanFavorite, editableValue: @"""S1""")); } } }
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/VisualBasicTest/SplitOrMergeIfStatements/MergeConsecutiveIfStatementsTests_Statements_WithNext.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.SplitOrMergeIfStatements Partial Public NotInheritable Class MergeConsecutiveIfStatementsTests <Theory> <InlineData("[||]if a then")> <InlineData("i[||]f a then")> <InlineData("if[||] a then")> <InlineData("if a [||]then")> <InlineData("if a th[||]en")> <InlineData("if a then[||]")> <InlineData("[|if|] a then")> <InlineData("[|if a then|]")> Public Async Function MergedIntoNextStatementOnIfSpans(ifLine As String) As Task Await TestInRegularAndScriptAsync( $"class C sub M(a as boolean, b as boolean) {ifLine} return end if if b then return end if end sub end class", "class C sub M(a as boolean, b as boolean) if a OrElse b then return end if end sub end class") End Function <Fact> Public Async Function MergedIntoNextStatementOnIfExtendedStatementSelection() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) [| if a then |] return end if if b then return end if end sub end class", "class C sub M(a as boolean, b as boolean) if a OrElse b then return end if end sub end class") End Function <Theory> <InlineData("if [||]a then")> <InlineData("[|i|]f a then")> <InlineData("[|if a|] then")> <InlineData("if [|a|] then")> <InlineData("if a [|then|]")> Public Async Function NotMergedIntoNextStatementOnIfSpans(ifLine As String) As Task Await TestMissingInRegularAndScriptAsync( $"class C sub M(a as boolean, b as boolean) {ifLine} return end if if b then return end if end sub end class") End Function <Fact> Public Async Function NotMergedIntoNextStatementOnIfOverreachingSelection() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) [|if a then |] return end if if b then return end if end sub end class") End Function <Fact> Public Async Function NotMergedIntoNextStatementOnIfBodyStatementSelection() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then [|return|] end if if b then return end if end sub end class") End Function <Fact> Public Async Function MergedIntoStatementOnMiddleIfMergableWithNextOnly() As Task Const Initial As String = "class C sub M(a as boolean, b as boolean, c as boolean) if a then return else return end if [||]if b then return end if if c then return end if end sub end class" Const Expected As String = "class C sub M(a as boolean, b as boolean, c as boolean) if a then return else return end if if b OrElse c then return end if end sub end class" Await TestActionCountAsync(Initial, 1) Await TestInRegularAndScriptAsync(Initial, Expected) End Function <Fact> Public Async Function MergedIntoStatementOnMiddleIfMergableWithPreviousOnly() As Task Const Initial As String = "class C sub M(a as boolean, b as boolean, c as boolean) if a then return end if [||]if b then return else return end if if c then return end if end sub end class" Const Expected As String = "class C sub M(a as boolean, b as boolean, c as boolean) if a OrElse b then return else return end if if c then return end if end sub end class" Await TestActionCountAsync(Initial, 1) Await TestInRegularAndScriptAsync(Initial, Expected) End Function <Fact> Public Async Function MergedIntoStatementOnMiddleIfMergableWithBoth() As Task Const Initial As String = "class C sub M(a as boolean, b as boolean, c as boolean) if a then return end if [||]if b then return end if if c then return end if end sub end class" Const Expected1 As String = "class C sub M(a as boolean, b as boolean, c as boolean) if a OrElse b then return end if if c then return end if end sub end class" Const Expected2 As String = "class C sub M(a as boolean, b as boolean, c as boolean) if a then return end if if b OrElse c then return end if end sub end class" Await TestActionCountAsync(Initial, 2) Await TestInRegularAndScriptAsync(Initial, Expected1, index:=0) Await TestInRegularAndScriptAsync(Initial, Expected2, index:=1) 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. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SplitOrMergeIfStatements Partial Public NotInheritable Class MergeConsecutiveIfStatementsTests <Theory> <InlineData("[||]if a then")> <InlineData("i[||]f a then")> <InlineData("if[||] a then")> <InlineData("if a [||]then")> <InlineData("if a th[||]en")> <InlineData("if a then[||]")> <InlineData("[|if|] a then")> <InlineData("[|if a then|]")> Public Async Function MergedIntoNextStatementOnIfSpans(ifLine As String) As Task Await TestInRegularAndScriptAsync( $"class C sub M(a as boolean, b as boolean) {ifLine} return end if if b then return end if end sub end class", "class C sub M(a as boolean, b as boolean) if a OrElse b then return end if end sub end class") End Function <Fact> Public Async Function MergedIntoNextStatementOnIfExtendedStatementSelection() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) [| if a then |] return end if if b then return end if end sub end class", "class C sub M(a as boolean, b as boolean) if a OrElse b then return end if end sub end class") End Function <Theory> <InlineData("if [||]a then")> <InlineData("[|i|]f a then")> <InlineData("[|if a|] then")> <InlineData("if [|a|] then")> <InlineData("if a [|then|]")> Public Async Function NotMergedIntoNextStatementOnIfSpans(ifLine As String) As Task Await TestMissingInRegularAndScriptAsync( $"class C sub M(a as boolean, b as boolean) {ifLine} return end if if b then return end if end sub end class") End Function <Fact> Public Async Function NotMergedIntoNextStatementOnIfOverreachingSelection() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) [|if a then |] return end if if b then return end if end sub end class") End Function <Fact> Public Async Function NotMergedIntoNextStatementOnIfBodyStatementSelection() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a then [|return|] end if if b then return end if end sub end class") End Function <Fact> Public Async Function MergedIntoStatementOnMiddleIfMergableWithNextOnly() As Task Const Initial As String = "class C sub M(a as boolean, b as boolean, c as boolean) if a then return else return end if [||]if b then return end if if c then return end if end sub end class" Const Expected As String = "class C sub M(a as boolean, b as boolean, c as boolean) if a then return else return end if if b OrElse c then return end if end sub end class" Await TestActionCountAsync(Initial, 1) Await TestInRegularAndScriptAsync(Initial, Expected) End Function <Fact> Public Async Function MergedIntoStatementOnMiddleIfMergableWithPreviousOnly() As Task Const Initial As String = "class C sub M(a as boolean, b as boolean, c as boolean) if a then return end if [||]if b then return else return end if if c then return end if end sub end class" Const Expected As String = "class C sub M(a as boolean, b as boolean, c as boolean) if a OrElse b then return else return end if if c then return end if end sub end class" Await TestActionCountAsync(Initial, 1) Await TestInRegularAndScriptAsync(Initial, Expected) End Function <Fact> Public Async Function MergedIntoStatementOnMiddleIfMergableWithBoth() As Task Const Initial As String = "class C sub M(a as boolean, b as boolean, c as boolean) if a then return end if [||]if b then return end if if c then return end if end sub end class" Const Expected1 As String = "class C sub M(a as boolean, b as boolean, c as boolean) if a OrElse b then return end if if c then return end if end sub end class" Const Expected2 As String = "class C sub M(a as boolean, b as boolean, c as boolean) if a then return end if if b OrElse c then return end if end sub end class" Await TestActionCountAsync(Initial, 2) Await TestInRegularAndScriptAsync(Initial, Expected1, index:=0) Await TestInRegularAndScriptAsync(Initial, Expected2, index:=1) End Function End Class End Namespace
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/MSBuildTask/MvidReader.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.Diagnostics.CodeAnalysis; using System.IO; namespace Microsoft.CodeAnalysis.BuildTasks { public static class MvidReader { private static readonly Guid s_empty = Guid.Empty; public static Guid ReadAssemblyMvidOrEmpty(Stream stream) { return ReadAssemblyMvidOrEmpty(new BinaryReader(stream)); } private static Guid ReadAssemblyMvidOrEmpty(BinaryReader reader) { // DOS Header: Magic number (2) if (!ReadUInt16(reader, out ushort magicNumber) || magicNumber != 0x5a4d) // "MZ" { return s_empty; } // DOS Header: Address of PE Signature (at 0x3C) if (!MoveTo(0x3C, reader)) { return s_empty; } if (!ReadUInt32(reader, out uint pointerToPeSignature)) { return s_empty; } // jump over the MS DOS Stub to the PE Signature if (!MoveTo(pointerToPeSignature, reader)) { return s_empty; } // PE Signature ('P' 'E' null null) if (!ReadUInt32(reader, out uint peSig) || peSig != 0x00004550) { return s_empty; } // COFF Header: Machine (2) if (!Skip(2, reader)) { return s_empty; } // COFF Header: NumberOfSections (2) if (!ReadUInt16(reader, out ushort sections)) { return s_empty; } // COFF Header: TimeDateStamp (4), PointerToSymbolTable (4), NumberOfSymbols (4) if (!Skip(12, reader)) { return s_empty; } // COFF Header: OptionalHeaderSize (2) if (!ReadUInt16(reader, out ushort optionalHeaderSize)) { return s_empty; } // COFF Header: Characteristics (2) if (!Skip(2, reader)) { return s_empty; } // Optional header if (!Skip(optionalHeaderSize, reader)) { return s_empty; } // Section headers return FindMvidInSections(sections, reader); } private static Guid FindMvidInSections(ushort count, BinaryReader reader) { for (int i = 0; i < count; i++) { // Section: Name (8) if (!ReadBytes(reader, 8, out byte[]? name)) { return s_empty; } if (name!.Length == 8 && name[0] == '.' && name[1] == 'm' && name[2] == 'v' && name[3] == 'i' && name[4] == 'd' && name[5] == '\0') { // Section: VirtualSize (4) if (!ReadUInt32(reader, out uint virtualSize) || virtualSize != 16) { // The .mvid section only stores a Guid return s_empty; } // Section: VirtualAddress (4), SizeOfRawData (4) if (!Skip(8, reader)) { return s_empty; } // Section: PointerToRawData (4) if (!ReadUInt32(reader, out uint pointerToRawData)) { return s_empty; } return ReadMvidSection(reader, pointerToRawData); } else { // Section: VirtualSize (4), VirtualAddress (4), SizeOfRawData (4), // PointerToRawData (4), PointerToRelocations (4), PointerToLineNumbers (4), // NumberOfRelocations (2), NumberOfLineNumbers (2), Characteristics (4) if (!Skip(4 + 4 + 4 + 4 + 4 + 4 + 2 + 2 + 4, reader)) { return s_empty; } } } return s_empty; } private static Guid ReadMvidSection(BinaryReader reader, uint pointerToMvidSection) { if (!MoveTo(pointerToMvidSection, reader)) { return s_empty; } if (!ReadBytes(reader, 16, out byte[]? guidBytes)) { return s_empty; } return new Guid(guidBytes!); } private static bool ReadUInt16(BinaryReader reader, out ushort output) { if (reader.BaseStream.Position + 2 >= reader.BaseStream.Length) { output = 0; return false; } output = reader.ReadUInt16(); return true; } private static bool ReadUInt32(BinaryReader reader, out uint output) { if (reader.BaseStream.Position + 4 >= reader.BaseStream.Length) { output = 0; return false; } output = reader.ReadUInt32(); return true; } private static bool ReadBytes(BinaryReader reader, int count, out byte[]? output) { if (reader.BaseStream.Position + count >= reader.BaseStream.Length) { output = null; return false; } output = reader.ReadBytes(count); return true; } private static bool Skip(int bytes, BinaryReader reader) { if (reader.BaseStream.Position + bytes >= reader.BaseStream.Length) { return false; } reader.BaseStream.Seek(bytes, SeekOrigin.Current); return true; } private static bool MoveTo(uint position, BinaryReader reader) { if (position >= reader.BaseStream.Length) { return false; } reader.BaseStream.Seek(position, SeekOrigin.Begin); return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.CodeAnalysis; using System.IO; namespace Microsoft.CodeAnalysis.BuildTasks { public static class MvidReader { private static readonly Guid s_empty = Guid.Empty; public static Guid ReadAssemblyMvidOrEmpty(Stream stream) { return ReadAssemblyMvidOrEmpty(new BinaryReader(stream)); } private static Guid ReadAssemblyMvidOrEmpty(BinaryReader reader) { // DOS Header: Magic number (2) if (!ReadUInt16(reader, out ushort magicNumber) || magicNumber != 0x5a4d) // "MZ" { return s_empty; } // DOS Header: Address of PE Signature (at 0x3C) if (!MoveTo(0x3C, reader)) { return s_empty; } if (!ReadUInt32(reader, out uint pointerToPeSignature)) { return s_empty; } // jump over the MS DOS Stub to the PE Signature if (!MoveTo(pointerToPeSignature, reader)) { return s_empty; } // PE Signature ('P' 'E' null null) if (!ReadUInt32(reader, out uint peSig) || peSig != 0x00004550) { return s_empty; } // COFF Header: Machine (2) if (!Skip(2, reader)) { return s_empty; } // COFF Header: NumberOfSections (2) if (!ReadUInt16(reader, out ushort sections)) { return s_empty; } // COFF Header: TimeDateStamp (4), PointerToSymbolTable (4), NumberOfSymbols (4) if (!Skip(12, reader)) { return s_empty; } // COFF Header: OptionalHeaderSize (2) if (!ReadUInt16(reader, out ushort optionalHeaderSize)) { return s_empty; } // COFF Header: Characteristics (2) if (!Skip(2, reader)) { return s_empty; } // Optional header if (!Skip(optionalHeaderSize, reader)) { return s_empty; } // Section headers return FindMvidInSections(sections, reader); } private static Guid FindMvidInSections(ushort count, BinaryReader reader) { for (int i = 0; i < count; i++) { // Section: Name (8) if (!ReadBytes(reader, 8, out byte[]? name)) { return s_empty; } if (name!.Length == 8 && name[0] == '.' && name[1] == 'm' && name[2] == 'v' && name[3] == 'i' && name[4] == 'd' && name[5] == '\0') { // Section: VirtualSize (4) if (!ReadUInt32(reader, out uint virtualSize) || virtualSize != 16) { // The .mvid section only stores a Guid return s_empty; } // Section: VirtualAddress (4), SizeOfRawData (4) if (!Skip(8, reader)) { return s_empty; } // Section: PointerToRawData (4) if (!ReadUInt32(reader, out uint pointerToRawData)) { return s_empty; } return ReadMvidSection(reader, pointerToRawData); } else { // Section: VirtualSize (4), VirtualAddress (4), SizeOfRawData (4), // PointerToRawData (4), PointerToRelocations (4), PointerToLineNumbers (4), // NumberOfRelocations (2), NumberOfLineNumbers (2), Characteristics (4) if (!Skip(4 + 4 + 4 + 4 + 4 + 4 + 2 + 2 + 4, reader)) { return s_empty; } } } return s_empty; } private static Guid ReadMvidSection(BinaryReader reader, uint pointerToMvidSection) { if (!MoveTo(pointerToMvidSection, reader)) { return s_empty; } if (!ReadBytes(reader, 16, out byte[]? guidBytes)) { return s_empty; } return new Guid(guidBytes!); } private static bool ReadUInt16(BinaryReader reader, out ushort output) { if (reader.BaseStream.Position + 2 >= reader.BaseStream.Length) { output = 0; return false; } output = reader.ReadUInt16(); return true; } private static bool ReadUInt32(BinaryReader reader, out uint output) { if (reader.BaseStream.Position + 4 >= reader.BaseStream.Length) { output = 0; return false; } output = reader.ReadUInt32(); return true; } private static bool ReadBytes(BinaryReader reader, int count, out byte[]? output) { if (reader.BaseStream.Position + count >= reader.BaseStream.Length) { output = null; return false; } output = reader.ReadBytes(count); return true; } private static bool Skip(int bytes, BinaryReader reader) { if (reader.BaseStream.Position + bytes >= reader.BaseStream.Length) { return false; } reader.BaseStream.Seek(bytes, SeekOrigin.Current); return true; } private static bool MoveTo(uint position, BinaryReader reader) { if (position >= reader.BaseStream.Length) { return false; } reader.BaseStream.Seek(position, SeekOrigin.Begin); return true; } } }
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./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,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/Matcher.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; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal class Matcher { /// <summary> /// Matcher equivalent to (m*) /// </summary> public static Matcher<T> Repeat<T>(Matcher<T> matcher) => Matcher<T>.Repeat(matcher); /// <summary> /// Matcher equivalent to (m+) /// </summary> public static Matcher<T> OneOrMore<T>(Matcher<T> matcher) => Matcher<T>.OneOrMore(matcher); /// <summary> /// Matcher equivalent to (m_1|m_2|...|m_n) /// </summary> public static Matcher<T> Choice<T>(params Matcher<T>[] matchers) => Matcher<T>.Choice(matchers); /// <summary> /// Matcher equivalent to (m_1 ... m_n) /// </summary> public static Matcher<T> Sequence<T>(params Matcher<T>[] matchers) => Matcher<T>.Sequence(matchers); /// <summary> /// Matcher that matches an element if the provide predicate returns true. /// </summary> public static Matcher<T> Single<T>(Func<T, bool> predicate, string description) => Matcher<T>.Single(predicate, description); } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal class Matcher { /// <summary> /// Matcher equivalent to (m*) /// </summary> public static Matcher<T> Repeat<T>(Matcher<T> matcher) => Matcher<T>.Repeat(matcher); /// <summary> /// Matcher equivalent to (m+) /// </summary> public static Matcher<T> OneOrMore<T>(Matcher<T> matcher) => Matcher<T>.OneOrMore(matcher); /// <summary> /// Matcher equivalent to (m_1|m_2|...|m_n) /// </summary> public static Matcher<T> Choice<T>(params Matcher<T>[] matchers) => Matcher<T>.Choice(matchers); /// <summary> /// Matcher equivalent to (m_1 ... m_n) /// </summary> public static Matcher<T> Sequence<T>(params Matcher<T>[] matchers) => Matcher<T>.Sequence(matchers); /// <summary> /// Matcher that matches an element if the provide predicate returns true. /// </summary> public static Matcher<T> Single<T>(Func<T, bool> predicate, string description) => Matcher<T>.Single(predicate, description); } }
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/VisualBasic/Portable/VBFeaturesResources.resx
<?xml version="1.0" encoding="utf-8"?> <root> <!-- Microsoft ResX Schema Version 2.0 The primary goals of this format is to allow a simple XML format that is mostly human readable. The generation and parsing of the various data types are done through the TypeConverter classes associated with the data types. Example: ... ado.net/XML headers & schema ... <resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="version">2.0</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> <value>[base64 mime encoded serialized .NET Framework object]</value> </data> <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <comment>This is a comment</comment> </data> There are any number of "resheader" rows that contain simple name/value pairs. Each data row contains a name, and value. The row also contains a type or mimetype. Type corresponds to a .NET class that support text/value conversion through the TypeConverter architecture. Classes that don't support this are serialized and stored with the mimetype set. The mimetype is used for serialized objects, and tells the ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly: Note - application/x-microsoft.net.object.binary.base64 is the format that the ResXResourceWriter will generate, however the reader can read any of the formats listed below. mimetype: application/x-microsoft.net.object.binary.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.soap.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.bytearray.base64 value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> <xsd:element name="root" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="metadata"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" /> </xsd:sequence> <xsd:attribute name="name" use="required" type="xsd:string" /> <xsd:attribute name="type" type="xsd:string" /> <xsd:attribute name="mimetype" type="xsd:string" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="assembly"> <xsd:complexType> <xsd:attribute name="alias" type="xsd:string" /> <xsd:attribute name="name" type="xsd:string" /> </xsd:complexType> </xsd:element> <xsd:element name="data"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="resheader"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <resheader name="version"> <value>2.0</value> </resheader> <resheader name="reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <data name="Insert_0" xml:space="preserve"> <value>Insert '{0}'.</value> </data> <data name="Delete_the_0_statement1" xml:space="preserve"> <value>Delete the '{0}' statement.</value> </data> <data name="Create_event_0_in_1" xml:space="preserve"> <value>Create event {0} in {1}</value> </data> <data name="Insert_the_missing_End_Property_statement" xml:space="preserve"> <value>Insert the missing 'End Property' statement.</value> </data> <data name="Insert_the_missing_0" xml:space="preserve"> <value>Insert the missing '{0}'.</value> </data> <data name="Inline_temporary_variable" xml:space="preserve"> <value>Inline temporary variable</value> </data> <data name="Conflict_s_detected" xml:space="preserve"> <value>Conflict(s) detected.</value> </data> <data name="Invert_If" xml:space="preserve"> <value>Invert If</value> </data> <data name="Add_Await" xml:space="preserve"> <value>Add Await</value> </data> <data name="Add_Await_and_ConfigureAwaitFalse" xml:space="preserve"> <value>Add Await and 'ConfigureAwait(false)'</value> </data> <data name="Move_the_0_statement_to_line_1" xml:space="preserve"> <value>Move the '{0}' statement to line {1}.</value> </data> <data name="Delete_the_0_statement2" xml:space="preserve"> <value>Delete the '{0}' statement.</value> </data> <data name="Type_a_name_here_to_declare_a_new_field" xml:space="preserve"> <value>Type a name here to declare a new field.</value> </data> <data name="Note_colon_Space_completion_is_disabled_to_avoid_potential_interference_To_insert_a_name_from_the_list_use_tab" xml:space="preserve"> <value>Note: Space completion is disabled to avoid potential interference. To insert a name from the list, use tab.</value> </data> <data name="new_field" xml:space="preserve"> <value>&lt;new field&gt;</value> </data> <data name="Type_a_name_here_to_declare_a_parameter_If_no_preceding_keyword_is_used_ByVal_will_be_assumed_and_the_argument_will_be_passed_by_value" xml:space="preserve"> <value>Type a name here to declare a parameter. If no preceding keyword is used; 'ByVal' will be assumed and the argument will be passed by value.</value> </data> <data name="parameter_name" xml:space="preserve"> <value>&lt;parameter name&gt;</value> </data> <data name="Type_a_new_name_for_the_column_followed_by_Otherwise_the_original_column_name_with_be_used" xml:space="preserve"> <value>Type a new name for the column, followed by '='. Otherwise, the original column name with be used.</value> </data> <data name="Note_colon_Use_tab_for_automatic_completion_space_completion_is_disabled_to_avoid_interfering_with_a_new_name" xml:space="preserve"> <value>Note: Use tab for automatic completion; space completion is disabled to avoid interfering with a new name.</value> </data> <data name="result_alias" xml:space="preserve"> <value>&lt;result alias&gt;</value> </data> <data name="Type_a_new_variable_name" xml:space="preserve"> <value>Type a new variable name</value> </data> <data name="Note_colon_Space_and_completion_are_disabled_to_avoid_potential_interference_To_insert_a_name_from_the_list_use_tab" xml:space="preserve"> <value>Note: Space and '=' completion are disabled to avoid potential interference. To insert a name from the list, use tab.</value> </data> <data name="new_resource" xml:space="preserve"> <value>&lt;new resource&gt;</value> </data> <data name="AddHandler_statement" xml:space="preserve"> <value>AddHandler statement</value> </data> <data name="RemoveHandler_statement" xml:space="preserve"> <value>RemoveHandler statement</value> </data> <data name="_0_function" xml:space="preserve"> <value>{0} function</value> </data> <data name="CType_function" xml:space="preserve"> <value>CType function</value> </data> <data name="DirectCast_function" xml:space="preserve"> <value>DirectCast function</value> </data> <data name="TryCast_function" xml:space="preserve"> <value>TryCast function</value> </data> <data name="GetType_function" xml:space="preserve"> <value>GetType function</value> </data> <data name="GetXmlNamespace_function" xml:space="preserve"> <value>GetXmlNamespace function</value> </data> <data name="Mid_statement" xml:space="preserve"> <value>Mid statement</value> </data> <data name="Fix_Incorrect_Function_Return_Type" xml:space="preserve"> <value>Fix Incorrect Function Return Type</value> </data> <data name="Simplify_name_0" xml:space="preserve"> <value>Simplify name '{0}'</value> </data> <data name="Simplify_member_access_0" xml:space="preserve"> <value>Simplify member access '{0}'</value> </data> <data name="Remove_Me_qualification" xml:space="preserve"> <value>Remove 'Me' qualification</value> <comment>{Locked="Me"} "Me" is a VB keyword and should not be localized.</comment> </data> <data name="Name_can_be_simplified" xml:space="preserve"> <value>Name can be simplified</value> </data> <data name="can_t_determine_valid_range_of_statements_to_extract_out" xml:space="preserve"> <value>can't determine valid range of statements to extract out</value> </data> <data name="Not_all_code_paths_return" xml:space="preserve"> <value>Not all code paths return</value> </data> <data name="contains_invalid_selection" xml:space="preserve"> <value>contains invalid selection</value> </data> <data name="the_selection_contains_syntactic_errors" xml:space="preserve"> <value>the selection contains syntactic errors</value> </data> <data name="Selection_can_t_be_crossed_over_preprocessors" xml:space="preserve"> <value>Selection can't be crossed over preprocessors</value> </data> <data name="Selection_can_t_contain_throw_without_enclosing_catch_block" xml:space="preserve"> <value>Selection can't contain throw without enclosing catch block</value> </data> <data name="Selection_can_t_be_parts_of_constant_initializer_expression" xml:space="preserve"> <value>Selection can't be parts of constant initializer expression</value> </data> <data name="Argument_used_for_ByRef_parameter_can_t_be_extracted_out" xml:space="preserve"> <value>Argument used for ByRef parameter can't be extracted out</value> </data> <data name="all_static_local_usages_defined_in_the_selection_must_be_included_in_the_selection" xml:space="preserve"> <value>all static local usages defined in the selection must be included in the selection</value> </data> <data name="Implicit_member_access_can_t_be_included_in_the_selection_without_containing_statement" xml:space="preserve"> <value>Implicit member access can't be included in the selection without containing statement</value> </data> <data name="Selection_must_be_part_of_executable_statements" xml:space="preserve"> <value>Selection must be part of executable statements</value> </data> <data name="next_statement_control_variable_doesn_t_have_matching_declaration_statement" xml:space="preserve"> <value>next statement control variable doesn't have matching declaration statement</value> </data> <data name="Selection_doesn_t_contain_any_valid_node" xml:space="preserve"> <value>Selection doesn't contain any valid node</value> </data> <data name="no_valid_statement_range_to_extract_out" xml:space="preserve"> <value>no valid statement range to extract out</value> </data> <data name="Invalid_selection" xml:space="preserve"> <value>Invalid selection</value> </data> <data name="Selection_doesn_t_contain_any_valid_token" xml:space="preserve"> <value>Selection doesn't contain any valid token</value> </data> <data name="No_valid_selection_to_perform_extraction" xml:space="preserve"> <value>No valid selection to perform extraction</value> </data> <data name="No_common_root_node_for_extraction" xml:space="preserve"> <value>No common root node for extraction</value> </data> <data name="Deprecated" xml:space="preserve"> <value>Deprecated</value> </data> <data name="Extension" xml:space="preserve"> <value>Extension</value> </data> <data name="Awaitable" xml:space="preserve"> <value>Awaitable</value> </data> <data name="Awaitable_Extension" xml:space="preserve"> <value>Awaitable, Extension</value> </data> <data name="new_variable" xml:space="preserve"> <value>&lt;new variable&gt;</value> </data> <data name="Creates_a_delegate_procedure_instance_that_references_the_specified_procedure_AddressOf_procedureName" xml:space="preserve"> <value>Creates a delegate procedure instance that references the specified procedure. AddressOf &lt;procedureName&gt;</value> </data> <data name="Indicates_that_an_external_procedure_has_another_name_in_its_DLL" xml:space="preserve"> <value>Indicates that an external procedure has another name in its DLL.</value> </data> <data name="Performs_a_short_circuit_logical_conjunction_on_two_expressions_Returns_True_if_both_operands_evaluate_to_True_If_the_first_expression_evaluates_to_False_the_second_is_not_evaluated_result_expression1_AndAlso_expression2" xml:space="preserve"> <value>Performs a short-circuit logical conjunction on two expressions. Returns True if both operands evaluate to True. If the first expression evaluates to False, the second is not evaluated. &lt;result&gt; = &lt;expression1&gt; AndAlso &lt;expression2&gt;</value> </data> <data name="Performs_a_logical_conjunction_on_two_Boolean_expressions_or_a_bitwise_conjunction_on_two_numeric_expressions_For_Boolean_expressions_returns_True_if_both_operands_evaluate_to_True_Both_expressions_are_always_evaluated_result_expression1_And_expression2" xml:space="preserve"> <value>Performs a logical conjunction on two Boolean expressions, or a bitwise conjunction on two numeric expressions. For Boolean expressions, returns True if both operands evaluate to True. Both expressions are always evaluated. &lt;result&gt; = &lt;expression1&gt; And &lt;expression2&gt;</value> </data> <data name="Used_in_a_Declare_statement_The_Ansi_modifier_specifies_that_Visual_Basic_should_marshal_all_strings_to_ANSI_values_and_should_look_up_the_procedure_without_modifying_its_name_during_the_search_If_no_character_set_is_specified_ANSI_is_the_default" xml:space="preserve"> <value>Used in a Declare statement. The Ansi modifier specifies that Visual Basic should marshal all strings to ANSI values, and should look up the procedure without modifying its name during the search. If no character set is specified, ANSI is the default.</value> </data> <data name="Specifies_a_data_type_in_a_declaration_statement" xml:space="preserve"> <value>Specifies a data type in a declaration statement.</value> </data> <data name="Specifies_that_an_attribute_at_the_beginning_of_a_source_file_applies_to_the_entire_assembly_Otherwise_the_attribute_will_apply_only_to_an_individual_programming_element_such_as_a_class_or_property" xml:space="preserve"> <value>Specifies that an attribute at the beginning of a source file applies to the entire assembly. Otherwise the attribute will apply only to an individual programming element, such as a class or property.</value> </data> <data name="Indicates_an_asynchronous_method_that_can_use_the_Await_operator" xml:space="preserve"> <value>Indicates an asynchronous method that can use the Await operator.</value> </data> <data name="Used_in_a_Declare_statement_The_Auto_modifier_specifies_that_Visual_Basic_should_marshal_strings_according_to_NET_Framework_rules_and_should_determine_the_base_character_set_of_the_run_time_platform_and_possibly_modify_the_external_procedure_name_if_the_initial_search_fails" xml:space="preserve"> <value>Used in a Declare statement. The Auto modifier specifies that Visual Basic should marshal strings according to .NET Framework rules, and should determine the base character set of the run-time platform and possibly modify the external procedure name if the initial search fails.</value> </data> <data name="Specifies_that_an_argument_is_passed_in_such_a_way_that_the_called_procedure_can_change_the_underlying_value_of_the_argument_in_the_calling_code" xml:space="preserve"> <value>Specifies that an argument is passed in such a way that the called procedure can change the underlying value of the argument in the calling code.</value> </data> <data name="Specifies_that_an_argument_is_passed_in_such_a_way_that_the_called_procedure_or_property_cannot_change_the_underlying_value_of_the_argument_in_the_calling_code" xml:space="preserve"> <value>Specifies that an argument is passed in such a way that the called procedure or property cannot change the underlying value of the argument in the calling code.</value> </data> <data name="Declares_the_name_of_a_class_and_introduces_the_definitions_of_the_variables_properties_and_methods_that_make_up_the_class" xml:space="preserve"> <value>Declares the name of a class and introduces the definitions of the variables, properties, and methods that make up the class.</value> </data> <data name="Generates_a_string_concatenation_of_two_expressions" xml:space="preserve"> <value>Generates a string concatenation of two expressions.</value> </data> <data name="Declares_and_defines_one_or_more_constants" xml:space="preserve"> <value>Declares and defines one or more constants.</value> </data> <data name="Use_In_for_a_type_that_will_only_be_used_for_ByVal_arguments_to_functions" xml:space="preserve"> <value>Use 'In' for a type that will only be used for ByVal arguments to functions.</value> </data> <data name="Use_Out_for_a_type_that_will_only_be_used_as_a_return_from_functions" xml:space="preserve"> <value>Use 'Out' for a type that will only be used as a return from functions.</value> </data> <data name="Returns_the_result_of_explicitly_converting_an_expression_to_a_specified_data_type_object_structure_class_or_interface_CType_Object_As_Expression_Object_As_Type_As_Type" xml:space="preserve"> <value>Returns the result of explicitly converting an expression to a specified data type, object, structure, class, or interface. CType(Object As Expression, Object As Type) As Type</value> </data> <data name="Specifies_that_an_event_has_additional_specialized_code_for_adding_handlers_removing_handlers_and_raising_events" xml:space="preserve"> <value>Specifies that an event has additional, specialized code for adding handlers, removing handlers, and raising events.</value> </data> <data name="Declares_a_reference_to_a_procedure_implemented_in_an_external_file" xml:space="preserve"> <value>Declares a reference to a procedure implemented in an external file.</value> </data> <data name="Identifies_a_property_as_the_default_property_of_its_class_structure_or_interface" xml:space="preserve"> <value>Identifies a property as the default property of its class, structure, or interface.</value> </data> <data name="Used_to_declare_a_delegate_A_delegate_is_a_reference_type_that_refers_to_a_shared_method_of_a_type_or_to_an_instance_method_of_an_object_Any_procedure_that_is_convertible_or_that_has_matching_parameter_types_and_return_type_may_be_used_to_create_an_instance_of_this_delegate_class" xml:space="preserve"> <value>Used to declare a delegate. A delegate is a reference type that refers to a shared method of a type or to an instance method of an object. Any procedure that is convertible, or that has matching parameter types and return type may be used to create an instance of this delegate class.</value> </data> <data name="Declares_and_allocates_storage_space_for_one_or_more_variables_Dim_var_bracket_As_bracket_New_bracket_dataType_bracket_boundList_bracket_bracket_bracket_initializer_bracket_bracket_var2_bracket" xml:space="preserve"> <value>Declares and allocates storage space for one or more variables. Dim {&lt;var&gt; [As [New] dataType [(boundList)]][= initializer]}[, var2]</value> </data> <data name="Divides_two_numbers_and_returns_a_floating_point_result" xml:space="preserve"> <value>Divides two numbers and returns a floating-point result.</value> </data> <data name="Terminates_a_0_block" xml:space="preserve"> <value>Terminates a {0} block.</value> </data> <data name="Terminates_an_0_block" xml:space="preserve"> <value>Terminates an {0} block.</value> </data> <data name="Terminates_the_definition_of_a_0_statement" xml:space="preserve"> <value>Terminates the definition of a {0} statement.</value> </data> <data name="Terminates_the_definition_of_an_0_statement" xml:space="preserve"> <value>Terminates the definition of an {0} statement.</value> </data> <data name="Declares_an_enumeration_and_defines_the_values_of_its_members" xml:space="preserve"> <value>Declares an enumeration and defines the values of its members.</value> </data> <data name="Compares_two_expressions_and_returns_True_if_they_are_equal_Otherwise_returns_False" xml:space="preserve"> <value>Compares two expressions and returns True if they are equal. Otherwise, returns False.</value> </data> <data name="Used_to_release_array_variables_and_deallocate_the_memory_used_for_their_elements" xml:space="preserve"> <value>Used to release array variables and deallocate the memory used for their elements.</value> </data> <data name="Declares_a_user_defined_event" xml:space="preserve"> <value>Declares a user-defined event.</value> </data> <data name="Exits_a_Sub_procedure_and_transfers_execution_immediately_to_the_statement_following_the_call_to_the_Sub_procedure" xml:space="preserve"> <value>Exits a Sub procedure and transfers execution immediately to the statement following the call to the Sub procedure.</value> </data> <data name="Raises_a_number_to_the_power_of_another_number" xml:space="preserve"> <value>Raises a number to the power of another number.</value> </data> <data name="Specifies_that_the_external_procedure_being_referenced_in_the_Declare_statement_is_a_Function" xml:space="preserve"> <value>Specifies that the external procedure being referenced in the Declare statement is a Function.</value> </data> <data name="Specifies_that_the_external_procedure_being_referenced_in_the_Declare_statement_is_a_Sub" xml:space="preserve"> <value>Specifies that the external procedure being referenced in the Declare statement is a Sub.</value> </data> <data name="Specifies_that_one_or_more_declared_programming_elements_are_accessible_only_from_within_the_assembly_that_contains_their_declaration" xml:space="preserve"> <value>Specifies that one or more declared programming elements are accessible only from within the assembly that contains their declaration.</value> </data> <data name="Specifies_a_collection_and_a_range_variable_to_use_in_a_query" xml:space="preserve"> <value>Specifies a collection and a range variable to use in a query.</value> </data> <data name="Declares_the_name_parameters_and_code_that_define_a_Function_procedure_that_is_a_procedure_that_returns_a_value_to_the_calling_code" xml:space="preserve"> <value>Declares the name, parameters, and code that define a Function procedure, that is, a procedure that returns a value to the calling code.</value> </data> <data name="Constrains_a_generic_type_parameter_to_require_that_any_type_argument_passed_to_it_be_a_reference_type" xml:space="preserve"> <value>Constrains a generic type parameter to require that any type argument passed to it be a reference type.</value> </data> <data name="Specifies_a_constructor_constraint_on_a_generic_type_parameter" xml:space="preserve"> <value>Specifies a constructor constraint on a generic type parameter.</value> </data> <data name="Constrains_a_generic_type_parameter_to_require_that_any_type_argument_passed_to_it_be_a_value_type" xml:space="preserve"> <value>Constrains a generic type parameter to require that any type argument passed to it be a value type.</value> </data> <data name="Declares_a_Get_property_procedure_that_is_used_to_return_the_current_value_of_a_property" xml:space="preserve"> <value>Declares a Get property procedure that is used to return the current value of a property.</value> </data> <data name="Compares_two_expressions_and_returns_True_if_the_first_is_greater_than_the_second_Otherwise_returns_False" xml:space="preserve"> <value>Compares two expressions and returns True if the first is greater than the second. Otherwise, returns False.</value> </data> <data name="Compares_two_expressions_and_returns_True_if_the_first_is_greater_than_or_equal_to_the_second_Otherwise_returns_False" xml:space="preserve"> <value>Compares two expressions and returns True if the first is greater than or equal to the second. Otherwise, returns False.</value> </data> <data name="Declares_that_a_procedure_handles_a_specified_event" xml:space="preserve"> <value>Declares that a procedure handles a specified event.</value> </data> <data name="Indicates_that_a_class_or_structure_member_is_providing_the_implementation_for_a_member_defined_in_an_interface" xml:space="preserve"> <value>Indicates that a class or structure member is providing the implementation for a member defined in an interface.</value> </data> <data name="Specifies_one_or_more_interfaces_or_interface_members_that_must_be_implemented_in_the_class_or_structure_definition_in_which_the_Implements_statement_appears" xml:space="preserve"> <value>Specifies one or more interfaces, or interface members, that must be implemented in the class or structure definition in which the Implements statement appears.</value> </data> <data name="Imports_all_or_specified_elements_of_a_namespace_into_a_file" xml:space="preserve"> <value>Imports all or specified elements of a namespace into a file.</value> </data> <data name="Specifies_the_group_that_the_loop_variable_in_a_For_Each_statement_is_to_traverse" xml:space="preserve"> <value>Specifies the group that the loop variable in a For Each statement is to traverse.</value> </data> <data name="Specifies_the_group_that_the_loop_variable_is_to_traverse_in_a_For_Each_statement_or_specifies_the_range_variable_in_a_query" xml:space="preserve"> <value>Specifies the group that the loop variable is to traverse in a For Each statement, or specifies the range variable in a query.</value> </data> <data name="Causes_the_current_class_or_interface_to_inherit_the_attributes_variables_properties_procedures_and_events_from_another_class_or_set_of_interfaces" xml:space="preserve"> <value>Causes the current class or interface to inherit the attributes, variables, properties, procedures, and events from another class or set of interfaces.</value> </data> <data name="Specifies_the_group_that_the_range_variable_is_to_traverse_in_a_query" xml:space="preserve"> <value>Specifies the group that the range variable is to traverse in a query.</value> </data> <data name="Divides_two_numbers_and_returns_an_integer_result" xml:space="preserve"> <value>Divides two numbers and returns an integer result.</value> </data> <data name="Declares_the_name_of_an_interface_and_the_definitions_of_the_members_of_the_interface" xml:space="preserve"> <value>Declares the name of an interface and the definitions of the members of the interface.</value> </data> <data name="Determines_whether_an_expression_is_false_If_instances_of_any_class_or_structure_will_be_used_in_an_OrElse_clause_you_must_define_IsFalse_on_that_class_or_structure" xml:space="preserve"> <value>Determines whether an expression is false. If instances of any class or structure will be used in an OrElse clause, you must define IsFalse on that class or structure.</value> </data> <data name="Compares_two_object_reference_variables_and_returns_True_if_the_objects_are_equal_result_object1_Is_object2" xml:space="preserve"> <value>Compares two object reference variables and returns True if the objects are equal. &lt;result&gt; = &lt;object1&gt; Is &lt;object2&gt;</value> </data> <data name="Compares_two_object_reference_variables_and_returns_True_if_the_objects_are_not_equal_result_object1_IsNot_object2" xml:space="preserve"> <value>Compares two object reference variables and returns True if the objects are not equal. &lt;result&gt; = &lt;object1&gt; IsNot &lt;object2&gt;</value> </data> <data name="Determines_whether_an_expression_is_true_If_instances_of_any_class_or_structure_will_be_used_in_an_OrElse_clause_you_must_define_IsTrue_on_that_class_or_structure" xml:space="preserve"> <value>Determines whether an expression is true. If instances of any class or structure will be used in an OrElse clause, you must define IsTrue on that class or structure.</value> </data> <data name="Indicates_an_iterator_method_that_can_use_the_Yield_statement" xml:space="preserve"> <value>Indicates an iterator method that can use the Yield statement.</value> </data> <data name="Defines_an_iterator_lambda_expression_that_can_use_the_Yield_statement_Iterator_Function_parameterList_As_IEnumerable_Of_T" xml:space="preserve"> <value>Defines an iterator lambda expression that can use the Yield statement. Iterator Function(&lt;parameterList&gt;) As IEnumerable(Of &lt;T&gt;)</value> </data> <data name="Performs_an_arithmetic_left_shift_on_a_bit_pattern" xml:space="preserve"> <value>Performs an arithmetic left shift on a bit pattern.</value> </data> <data name="Compares_two_expressions_and_returns_True_if_the_first_is_less_than_the_second_Otherwise_returns_False" xml:space="preserve"> <value>Compares two expressions and returns True if the first is less than the second. Otherwise, returns False.</value> </data> <data name="Compares_two_expressions_and_returns_True_if_the_first_is_less_than_or_equal_to_the_second_Otherwise_returns_False" xml:space="preserve"> <value>Compares two expressions and returns True if the first is less than or equal to the second. Otherwise, returns False.</value> </data> <data name="Introduces_a_clause_that_identifies_the_external_file_DLL_or_code_resource_containing_an_external_procedure" xml:space="preserve"> <value>Introduces a clause that identifies the external file (DLL or code resource) containing an external procedure.</value> </data> <data name="Compares_a_string_against_a_pattern_Wildcards_available_include_to_match_1_character_and_to_match_0_or_more_characters_result_string_Like_pattern" xml:space="preserve"> <value>Compares a string against a pattern. Wildcards available include ? to match 1 character and * to match 0 or more characters. &lt;result&gt; = &lt;string&gt; Like &lt;pattern&gt;</value> </data> <data name="Returns_the_difference_between_two_numeric_expressions_or_the_negative_value_of_a_numeric_expression" xml:space="preserve"> <value>Returns the difference between two numeric expressions, or the negative value of a numeric expression.</value> </data> <data name="Divides_two_numbers_and_returns_only_the_remainder_number1_Mod_number2" xml:space="preserve"> <value>Divides two numbers and returns only the remainder. &lt;number1&gt; Mod &lt;number2&gt;</value> </data> <data name="Specifies_that_an_attribute_at_the_beginning_of_a_source_file_applies_to_the_entire_module_Otherwise_the_attribute_will_apply_only_to_an_individual_programming_element_such_as_a_class_or_property" xml:space="preserve"> <value>Specifies that an attribute at the beginning of a source file applies to the entire module. Otherwise the attribute will apply only to an individual programming element, such as a class or property.</value> </data> <data name="Multiplies_two_numbers_and_returns_the_product" xml:space="preserve"> <value>Multiplies two numbers and returns the product.</value> </data> <data name="Specifies_that_a_class_can_be_used_only_as_a_base_class_and_that_you_cannot_create_an_object_directly_from_it" xml:space="preserve"> <value>Specifies that a class can be used only as a base class, and that you cannot create an object directly from it.</value> </data> <data name="Specifies_that_a_property_or_procedure_is_not_implemented_in_the_class_and_must_be_overridden_in_a_derived_class_before_it_can_be_used" xml:space="preserve"> <value>Specifies that a property or procedure is not implemented in the class and must be overridden in a derived class before it can be used.</value> </data> <data name="Declares_the_name_of_a_namespace_and_causes_the_source_code_following_the_declaration_to_be_compiled_within_that_namespace" xml:space="preserve"> <value>Declares the name of a namespace, and causes the source code following the declaration to be compiled within that namespace.</value> </data> <data name="Indicates_that_a_conversion_operator_CType_converts_a_class_or_structure_to_a_type_that_might_not_be_able_to_hold_some_of_the_possible_values_of_the_original_class_or_structure" xml:space="preserve"> <value>Indicates that a conversion operator (CType) converts a class or structure to a type that might not be able to hold some of the possible values of the original class or structure.</value> </data> <data name="Compares_two_expressions_and_returns_True_if_they_are_not_equal_Otherwise_returns_False" xml:space="preserve"> <value>Compares two expressions and returns True if they are not equal. Otherwise, returns False.</value> </data> <data name="Specifies_that_a_class_cannot_be_used_as_a_base_class" xml:space="preserve"> <value>Specifies that a class cannot be used as a base class.</value> </data> <data name="Performs_logical_negation_on_a_Boolean_expression_or_bitwise_negation_on_a_numeric_expression_result_Not_expression" xml:space="preserve"> <value>Performs logical negation on a Boolean expression, or bitwise negation on a numeric expression. &lt;result&gt; = Not &lt;expression&gt;</value> </data> <data name="Specifies_that_a_property_or_procedure_cannot_be_overridden_in_a_derived_class" xml:space="preserve"> <value>Specifies that a property or procedure cannot be overridden in a derived class.</value> </data> <data name="Identifies_a_type_parameter_on_a_generic_class_structure_interface_delegate_or_procedure" xml:space="preserve"> <value>Identifies a type parameter on a generic class, structure, interface, delegate, or procedure.</value> </data> <data name="Declares_the_operator_symbol_operands_and_code_that_define_an_operator_procedure_on_a_class_or_structure" xml:space="preserve"> <value>Declares the operator symbol, operands, and code that define an operator procedure on a class or structure.</value> </data> <data name="Specifies_that_a_procedure_argument_can_be_omitted_when_the_procedure_is_called" xml:space="preserve"> <value>Specifies that a procedure argument can be omitted when the procedure is called.</value> </data> <data name="Introduces_a_statement_that_specifies_a_compiler_option_that_applies_to_the_entire_source_file" xml:space="preserve"> <value>Introduces a statement that specifies a compiler option that applies to the entire source file.</value> </data> <data name="Performs_short_circuit_inclusive_logical_disjunction_on_two_expressions_Returns_True_if_either_operand_evaluates_to_True_If_the_first_expression_evaluates_to_True_the_second_expression_is_not_evaluated_result_expression1_OrElse_expression2" xml:space="preserve"> <value>Performs short-circuit inclusive logical disjunction on two expressions. Returns True if either operand evaluates to True. If the first expression evaluates to True, the second expression is not evaluated. &lt;result&gt; = &lt;expression1&gt; OrElse &lt;expression2&gt;</value> </data> <data name="Performs_an_inclusive_logical_disjunction_on_two_Boolean_expressions_or_a_bitwise_disjunction_on_two_numeric_expressions_For_Boolean_expressions_returns_True_if_at_least_one_operand_evaluates_to_True_Both_expressions_are_always_evaluated_result_expression1_Or_expression2" xml:space="preserve"> <value>Performs an inclusive logical disjunction on two Boolean expressions, or a bitwise disjunction on two numeric expressions. For Boolean expressions, returns True if at least one operand evaluates to True. Both expressions are always evaluated. &lt;result&gt; = &lt;expression1&gt; Or &lt;expression2&gt;</value> </data> <data name="Specifies_that_a_property_or_procedure_re_declares_one_or_more_existing_properties_or_procedures_with_the_same_name" xml:space="preserve"> <value>Specifies that a property or procedure re-declares one or more existing properties or procedures with the same name.</value> </data> <data name="Specifies_that_a_property_or_procedure_can_be_overridden_by_an_identically_named_property_or_procedure_in_a_derived_class" xml:space="preserve"> <value>Specifies that a property or procedure can be overridden by an identically named property or procedure in a derived class.</value> </data> <data name="Specifies_that_a_property_or_procedure_overrides_an_identically_named_property_or_procedure_inherited_from_a_base_class" xml:space="preserve"> <value>Specifies that a property or procedure overrides an identically named property or procedure inherited from a base class.</value> </data> <data name="Specifies_that_a_procedure_parameter_takes_an_optional_array_of_elements_of_the_specified_type" xml:space="preserve"> <value>Specifies that a procedure parameter takes an optional array of elements of the specified type.</value> </data> <data name="Indicates_that_a_method_class_or_structure_declaration_is_a_partial_definition_of_the_method_class_or_structure" xml:space="preserve"> <value>Indicates that a method, class, or structure declaration is a partial definition of the method, class, or structure.</value> </data> <data name="Returns_the_sum_of_two_numbers_or_the_positive_value_of_a_numeric_expression" xml:space="preserve"> <value>Returns the sum of two numbers, or the positive value of a numeric expression.</value> </data> <data name="Prevents_the_contents_of_an_array_from_being_cleared_when_the_dimensions_of_the_array_are_changed" xml:space="preserve"> <value>Prevents the contents of an array from being cleared when the dimensions of the array are changed.</value> </data> <data name="Specifies_that_one_or_more_declared_programming_elements_are_accessible_only_from_within_their_module_class_or_structure" xml:space="preserve"> <value>Specifies that one or more declared programming elements are accessible only from within their module, class, or structure.</value> </data> <data name="Declares_the_name_of_a_property_and_the_property_procedures_used_to_store_and_retrieve_the_value_of_the_property" xml:space="preserve"> <value>Declares the name of a property, and the property procedures used to store and retrieve the value of the property.</value> </data> <data name="Specifies_that_one_or_more_declared_members_of_a_class_are_accessible_from_anywhere_in_the_same_assembly_their_own_classes_and_derived_classes" xml:space="preserve"> <value>Specifies that one or more declared members of a class are accessible from anywhere in the same assembly, their own classes, and derived classes.</value> </data> <data name="Specifies_that_one_or_more_declared_programming_elements_are_accessible_only_from_within_their_own_class_or_from_a_derived_class" xml:space="preserve"> <value>Specifies that one or more declared programming elements are accessible only from within their own class or from a derived class.</value> </data> <data name="Specifies_that_one_or_more_declared_programming_elements_have_no_access_restrictions" xml:space="preserve"> <value>Specifies that one or more declared programming elements have no access restrictions.</value> </data> <data name="Specifies_that_a_variable_or_property_can_be_read_but_not_written_to" xml:space="preserve"> <value>Specifies that a variable or property can be read but not written to.</value> </data> <data name="Reallocates_storage_space_for_an_array_variable" xml:space="preserve"> <value>Reallocates storage space for an array variable.</value> </data> <data name="Performs_an_arithmetic_right_shift_on_a_bit_pattern" xml:space="preserve"> <value>Performs an arithmetic right shift on a bit pattern</value> </data> <data name="Declares_a_Set_property_procedure_that_is_used_to_assign_a_value_to_a_property" xml:space="preserve"> <value>Declares a Set property procedure that is used to assign a value to a property.</value> </data> <data name="Specifies_that_a_declared_programming_element_redeclares_and_hides_an_identically_named_element_in_a_base_class" xml:space="preserve"> <value>Specifies that a declared programming element redeclares and hides an identically named element in a base class.</value> </data> <data name="Specifies_that_one_or_more_declared_programming_elements_are_associated_with_all_instances_of_a_class_or_structure" xml:space="preserve"> <value>Specifies that one or more declared programming elements are associated with all instances of a class or structure.</value> </data> <data name="Specifies_that_one_or_more_declared_local_variables_are_to_remain_in_existence_and_retain_their_latest_values_after_the_procedure_in_which_they_are_declared_terminates" xml:space="preserve"> <value>Specifies that one or more declared local variables are to remain in existence and retain their latest values after the procedure in which they are declared terminates.</value> </data> <data name="Declares_the_name_of_a_structure_and_introduces_the_definition_of_the_variables_properties_events_and_procedures_that_make_up_the_structure" xml:space="preserve"> <value>Declares the name of a structure and introduces the definition of the variables, properties, events, and procedures that make up the structure.</value> </data> <data name="Declares_the_name_parameters_and_code_that_define_a_Sub_procedure_that_is_a_procedure_that_does_not_return_a_value_to_the_calling_code" xml:space="preserve"> <value>Declares the name, parameters, and code that define a Sub procedure, that is, a procedure that does not return a value to the calling code.</value> </data> <data name="Separates_the_beginning_and_ending_values_of_a_loop_counter_or_array_bounds_or_that_of_a_value_match_range" xml:space="preserve"> <value>Separates the beginning and ending values of a loop counter or array bounds or that of a value match range.</value> </data> <data name="Determines_the_run_time_type_of_an_object_reference_variable_and_compares_it_to_a_data_type_Returns_True_or_False_depending_on_whether_the_two_types_are_compatible_result_TypeOf_objectExpression_Is_typeName" xml:space="preserve"> <value>Determines the run-time type of an object reference variable and compares it to a data type. Returns True or False depending, on whether the two types are compatible. &lt;result&gt; = TypeOf &lt;objectExpression&gt; Is &lt;typeName&gt;</value> </data> <data name="Used_in_a_Declare_statement_Specifies_that_Visual_Basic_should_marshal_all_strings_to_Unicode_values_in_a_call_into_an_external_procedure_and_should_look_up_the_procedure_without_modifying_its_name" xml:space="preserve"> <value>Used in a Declare statement. Specifies that Visual Basic should marshal all strings to Unicode values in a call into an external procedure, and should look up the procedure without modifying its name.</value> </data> <data name="Indicates_that_a_conversion_operator_CType_converts_a_class_or_structure_to_a_type_that_can_hold_all_possible_values_of_the_original_class_or_structure" xml:space="preserve"> <value>Indicates that a conversion operator (CType) converts a class or structure to a type that can hold all possible values of the original class or structure.</value> </data> <data name="Specifies_that_one_or_more_declared_member_variables_refer_to_an_instance_of_a_class_that_can_raise_events" xml:space="preserve"> <value>Specifies that one or more declared member variables refer to an instance of a class that can raise events</value> </data> <data name="Specifies_that_a_property_can_be_written_to_but_not_read" xml:space="preserve"> <value>Specifies that a property can be written to but not read.</value> </data> <data name="Performs_a_logical_exclusion_on_two_Boolean_expressions_or_a_bitwise_exclusion_on_two_numeric_expressions_For_Boolean_expressions_returns_True_if_exactly_one_of_the_expressions_evaluates_to_True_Both_expressions_are_always_evaluated_result_expression1_Xor_expression2" xml:space="preserve"> <value>Performs a logical exclusion on two Boolean expressions, or a bitwise exclusion on two numeric expressions. For Boolean expressions, returns True if exactly one of the expressions evaluates to True. Both expressions are always evaluated. &lt;result&gt; = &lt;expression1&gt; Xor &lt;expression2&gt;</value> </data> <data name="Applies_an_aggregation_function_such_as_Sum_Average_or_Count_to_a_sequence" xml:space="preserve"> <value>Applies an aggregation function, such as Sum, Average, or Count to a sequence.</value> </data> <data name="Specifies_the_sort_order_for_an_Order_By_clause_in_a_query_The_smallest_element_will_appear_first" xml:space="preserve"> <value>Specifies the sort order for an Order By clause in a query. The smallest element will appear first.</value> </data> <data name="Asynchronously_waits_for_the_task_to_finish" xml:space="preserve"> <value>Asynchronously waits for the task to finish.</value> </data> <data name="Sets_the_string_comparison_method_specified_in_Option_Compare_to_a_strict_binary_sort_order" xml:space="preserve"> <value>Sets the string comparison method specified in Option Compare to a strict binary sort order.</value> </data> <data name="Specifies_the_element_keys_used_for_grouping_in_Group_By_or_sort_order_in_Order_By" xml:space="preserve"> <value>Specifies the element keys used for grouping (in Group By) or sort order (in Order By).</value> </data> <data name="Transfers_execution_to_a_Function_Sub_or_dynamic_link_library_DLL_procedure_bracket_Call_bracket_procedureName_bracket_argumentList_bracket" xml:space="preserve"> <value>Transfers execution to a Function, Sub, or dynamic-link library (DLL) procedure. [Call] &lt;procedureName&gt; [(&lt;argumentList&gt;)]</value> </data> <data name="Introduces_the_statements_to_run_if_none_of_the_previous_cases_in_the_Select_Case_statement_returns_True" xml:space="preserve"> <value>Introduces the statements to run if none of the previous cases in the Select Case statement returns True.</value> </data> <data name="Followed_by_a_comparison_operator_and_then_an_expression_Case_Is_introduces_the_statements_to_run_if_the_Select_Case_expression_combined_with_the_Case_Is_expression_evaluates_to_True" xml:space="preserve"> <value>Followed by a comparison operator and then an expression, Case Is introduces the statements to run if the Select Case expression combined with the Case Is expression evaluates to True.</value> </data> <data name="Introduces_a_value_or_set_of_values_against_which_the_value_of_an_expression_in_a_Select_Case_statement_is_to_be_tested_Case_expression_expression1_To_expression2_bracket_Is_bracket_comparisonOperator_expression" xml:space="preserve"> <value>Introduces a value, or set of values, against which the value of an expression in a Select Case statement is to be tested. Case {&lt;expression&gt;|&lt;expression1&gt; To &lt;expression2&gt;|[Is] &lt;comparisonOperator&gt; &lt;expression&gt;}</value> </data> <data name="Introduces_a_statement_block_to_be_run_if_the_specified_exception_occurs_inside_a_Try_block" xml:space="preserve"> <value>Introduces a statement block to be run if the specified exception occurs inside a Try block.</value> </data> <data name="Sets_the_default_comparison_method_to_use_when_comparing_string_data_When_set_to_Text_uses_a_text_sort_order_that_is_not_case_sensitive_When_set_to_Binary_uses_a_strict_binary_sort_order_Option_Compare_Binary_Text" xml:space="preserve"> <value>Sets the default comparison method to use when comparing string data. When set to Text, uses a text sort order that is not case sensitive. When set to Binary, uses a strict binary sort order. Option Compare {Binary | Text}</value> </data> <data name="Defines_a_conditional_compiler_constant_Conditional_compiler_constants_are_always_private_to_the_file_in_which_they_appear_The_expressions_used_to_initialize_them_can_contain_only_conditional_compiler_constants_and_literals" xml:space="preserve"> <value>Defines a conditional compiler constant. Conditional compiler constants are always private to the file in which they appear. The expressions used to initialize them can contain only conditional compiler constants and literals.</value> </data> <data name="Transfers_execution_immediately_to_the_next_iteration_of_the_Do_loop" xml:space="preserve"> <value>Transfers execution immediately to the next iteration of the Do loop.</value> </data> <data name="Transfers_execution_immediately_to_the_next_iteration_of_the_For_loop" xml:space="preserve"> <value>Transfers execution immediately to the next iteration of the For loop.</value> </data> <data name="Transfers_execution_immediately_to_the_next_iteration_of_the_loop_Can_be_used_in_a_Do_loop_a_For_loop_or_a_While_loop" xml:space="preserve"> <value>Transfers execution immediately to the next iteration of the loop. Can be used in a Do loop, a For loop, or a While loop.</value> </data> <data name="Transfers_execution_immediately_to_the_next_iteration_of_the_While_loop" xml:space="preserve"> <value>Transfers execution immediately to the next iteration of the While loop.</value> </data> <data name="Specifies_the_sort_order_for_an_Order_By_clause_in_a_query_The_largest_element_will_appear_first" xml:space="preserve"> <value>Specifies the sort order for an Order By clause in a query. The largest element will appear first.</value> </data> <data name="Restricts_the_values_of_a_query_result_to_eliminate_duplicate_values" xml:space="preserve"> <value>Restricts the values of a query result to eliminate duplicate values.</value> </data> <data name="Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_or_until_the_condition_becomes_true_Do_Loop_While_Until_condition" xml:space="preserve"> <value>Repeats a block of statements while a Boolean condition is true, or until the condition becomes true. Do...Loop {While | Until} &lt;condition&gt;</value> </data> <data name="Repeats_a_block_of_statements_until_a_Boolean_condition_becomes_true_Do_Until_condition_Loop" xml:space="preserve"> <value>Repeats a block of statements until a Boolean condition becomes true. Do Until &lt;condition&gt;...Loop</value> </data> <data name="Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_Do_While_condition_Loop" xml:space="preserve"> <value>Repeats a block of statements while a Boolean condition is true. Do While &lt;condition&gt;...Loop</value> </data> <data name="Introduces_a_group_of_statements_in_an_SharpIf_statement_that_is_compiled_if_no_previous_condition_evaluates_to_True" xml:space="preserve"> <value>Introduces a group of statements in an #If statement that is compiled if no previous condition evaluates to True.</value> </data> <data name="Introduces_a_condition_in_an_SharpIf_statement_that_is_tested_if_the_previous_conditional_test_evaluates_to_False" xml:space="preserve"> <value>Introduces a condition in an #If statement that is tested if the previous conditional test evaluates to False.</value> </data> <data name="Introduces_a_condition_in_an_If_statement_that_is_to_be_tested_if_the_previous_conditional_test_fails" xml:space="preserve"> <value>Introduces a condition in an If statement that is to be tested if the previous conditional test fails.</value> </data> <data name="Introduces_a_group_of_statements_in_an_If_statement_that_is_executed_if_no_previous_condition_evaluates_to_True" xml:space="preserve"> <value>Introduces a group of statements in an If statement that is executed if no previous condition evaluates to True.</value> </data> <data name="Terminates_the_definition_of_an_SharpIf_block" xml:space="preserve"> <value>Terminates the definition of an #If block.</value> </data> <data name="Stops_execution_immediately" xml:space="preserve"> <value>Stops execution immediately.</value> </data> <data name="Terminates_a_SharpRegion_block" xml:space="preserve"> <value>Terminates a #Region block.</value> </data> <data name="Specifies_the_relationship_between_element_keys_to_use_as_the_basis_of_a_join_operation" xml:space="preserve"> <value>Specifies the relationship between element keys to use as the basis of a join operation.</value> </data> <data name="Simulates_the_occurrence_of_an_error" xml:space="preserve"> <value>Simulates the occurrence of an error.</value> </data> <data name="Exits_a_Do_loop_and_transfers_execution_immediately_to_the_statement_following_the_Loop_statement" xml:space="preserve"> <value>Exits a Do loop and transfers execution immediately to the statement following the Loop statement.</value> </data> <data name="Exits_a_For_loop_and_transfers_execution_immediately_to_the_statement_following_the_Next_statement" xml:space="preserve"> <value>Exits a For loop and transfers execution immediately to the statement following the Next statement.</value> </data> <data name="Exits_a_procedure_or_block_and_transfers_execution_immediately_to_the_statement_following_the_procedure_call_or_block_definition_Exit_Do_For_Function_Property_Select_Sub_Try_While" xml:space="preserve"> <value>Exits a procedure or block and transfers execution immediately to the statement following the procedure call or block definition. Exit {Do | For | Function | Property | Select | Sub | Try | While}</value> </data> <data name="Exits_a_Select_block_and_transfers_execution_immediately_to_the_statement_following_the_End_Select_statement" xml:space="preserve"> <value>Exits a Select block and transfers execution immediately to the statement following the End Select statement.</value> </data> <data name="Exits_a_Try_block_and_transfers_execution_immediately_to_the_statement_following_the_End_Try_statement" xml:space="preserve"> <value>Exits a Try block and transfers execution immediately to the statement following the End Try statement.</value> </data> <data name="Exits_a_While_loop_and_transfers_execution_immediately_to_the_statement_following_the_End_While_statement" xml:space="preserve"> <value>Exits a While loop and transfers execution immediately to the statement following the End While statement.</value> </data> <data name="When_set_to_On_requires_explicit_declaration_of_all_variables_using_a_Dim_Private_Public_or_ReDim_statement_Option_Explicit_On_Off" xml:space="preserve"> <value>When set to On, requires explicit declaration of all variables, using a Dim, Private, Public, or ReDim statement. Option Explicit {On | Off}</value> </data> <data name="Represents_a_Boolean_value_that_fails_a_conditional_test" xml:space="preserve"> <value>Represents a Boolean value that fails a conditional test.</value> </data> <data name="Introduces_a_statement_block_to_be_run_before_exiting_a_Try_structure" xml:space="preserve"> <value>Introduces a statement block to be run before exiting a Try structure.</value> </data> <data name="Introduces_a_loop_that_is_repeated_for_each_element_in_a_collection" xml:space="preserve"> <value>Introduces a loop that is repeated for each element in a collection.</value> </data> <data name="Introduces_a_loop_that_is_iterated_a_specified_number_of_times" xml:space="preserve"> <value>Introduces a loop that is iterated a specified number of times.</value> </data> <data name="Identifies_a_list_of_values_as_a_collection_initializer" xml:space="preserve"> <value>Identifies a list of values as a collection initializer</value> </data> <data name="Branches_unconditionally_to_a_specified_line_in_a_procedure" xml:space="preserve"> <value>Branches unconditionally to a specified line in a procedure.</value> </data> <data name="Groups_elements_that_have_a_common_key" xml:space="preserve"> <value>Groups elements that have a common key.</value> </data> <data name="Combines_the_elements_of_two_sequences_and_groups_the_results_The_join_operation_is_based_on_matching_keys" xml:space="preserve"> <value>Combines the elements of two sequences and groups the results. The join operation is based on matching keys.</value> </data> <data name="Use_Group_to_specify_that_a_group_named_0_should_be_created" xml:space="preserve"> <value>Use 'Group' to specify that a group named '{0}' should be created.</value> </data> <data name="Use_Group_to_specify_that_a_group_named_Group_should_be_created" xml:space="preserve"> <value>Use 'Group' to specify that a group named 'Group' should be created.</value> </data> <data name="Conditionally_compiles_selected_blocks_of_code_depending_on_the_value_of_an_expression" xml:space="preserve"> <value>Conditionally compiles selected blocks of code, depending on the value of an expression.</value> </data> <data name="Conditionally_executes_a_group_of_statements_depending_on_the_value_of_an_expression" xml:space="preserve"> <value>Conditionally executes a group of statements, depending on the value of an expression.</value> </data> <data name="When_set_to_On_allows_the_use_of_local_type_inference_in_declaring_variables_Option_Infer_On_Off" xml:space="preserve"> <value>When set to On, allows the use of local type inference in declaring variables. Option Infer {On | Off}</value> </data> <data name="Specifies_an_identifier_that_can_serve_as_a_reference_to_the_results_of_a_join_or_grouping_subexpression" xml:space="preserve"> <value>Specifies an identifier that can serve as a reference to the results of a join or grouping subexpression.</value> </data> <data name="Combines_the_elements_of_two_sequences_The_join_operation_is_based_on_matching_keys" xml:space="preserve"> <value>Combines the elements of two sequences. The join operation is based on matching keys.</value> </data> <data name="Identifies_a_key_field_in_an_anonymous_type_definition" xml:space="preserve"> <value>Identifies a key field in an anonymous type definition.</value> </data> <data name="Computes_a_value_for_each_item_in_the_query_and_assigns_the_value_to_a_new_range_variable" xml:space="preserve"> <value>Computes a value for each item in the query, and assigns the value to a new range variable.</value> </data> <data name="Terminates_a_loop_that_is_introduced_with_a_Do_statement" xml:space="preserve"> <value>Terminates a loop that is introduced with a Do statement.</value> </data> <data name="Repeats_a_block_of_statements_until_a_Boolean_condition_becomes_true_Do_Loop_Until_condition" xml:space="preserve"> <value>Repeats a block of statements until a Boolean condition becomes true. Do...Loop Until &lt;condition&gt;</value> </data> <data name="Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_Do_Loop_While_condition" xml:space="preserve"> <value>Repeats a block of statements while a Boolean condition is true. Do...Loop While &lt;condition&gt;</value> </data> <data name="Provides_a_way_to_refer_to_the_current_instance_of_a_class_or_structure_that_is_the_instance_in_which_the_code_is_running" xml:space="preserve"> <value>Provides a way to refer to the current instance of a class or structure, that is, the instance in which the code is running.</value> </data> <data name="Provides_a_way_to_refer_to_the_base_class_of_the_current_class_instance_You_cannot_use_MyBase_to_call_MustOverride_base_methods" xml:space="preserve"> <value>Provides a way to refer to the base class of the current class instance. You cannot use MyBase to call MustOverride base methods.</value> </data> <data name="Provides_a_way_to_refer_to_the_class_instance_members_as_originally_implemented_ignoring_any_derived_class_overrides" xml:space="preserve"> <value>Provides a way to refer to the class instance members as originally implemented, ignoring any derived class overrides.</value> </data> <data name="Creates_a_new_object_instance" xml:space="preserve"> <value>Creates a new object instance.</value> </data> <data name="Terminates_a_loop_that_iterates_through_the_values_of_a_loop_variable" xml:space="preserve"> <value>Terminates a loop that iterates through the values of a loop variable.</value> </data> <data name="Represents_the_default_value_of_any_data_type" xml:space="preserve"> <value>Represents the default value of any data type.</value> </data> <data name="Turns_a_compiler_option_off" xml:space="preserve"> <value>Turns a compiler option off.</value> </data> <data name="Enables_the_error_handling_routine_that_starts_at_the_line_specified_in_the_line_argument_The_specified_line_must_be_in_the_same_procedure_as_the_On_Error_statement_On_Error_GoTo_bracket_label_0_1_bracket" xml:space="preserve"> <value>Enables the error-handling routine that starts at the line specified in the line argument. The specified line must be in the same procedure as the On Error statement. On Error GoTo [&lt;label&gt; | 0 | -1]</value> </data> <data name="When_a_run_time_error_occurs_execution_transfers_to_the_statement_following_the_statement_or_procedure_call_that_resulted_in_the_error" xml:space="preserve"> <value>When a run-time error occurs, execution transfers to the statement following the statement or procedure call that resulted in the error.</value> </data> <data name="Turns_a_compiler_option_on" xml:space="preserve"> <value>Turns a compiler option on.</value> </data> <data name="Specifies_the_element_keys_used_to_correlate_sequences_for_a_join_operation" xml:space="preserve"> <value>Specifies the element keys used to correlate sequences for a join operation.</value> </data> <data name="Specifies_the_sort_order_for_columns_in_a_query_Can_be_followed_by_either_the_Ascending_or_the_Descending_keyword_If_neither_is_specified_Ascending_is_used" xml:space="preserve"> <value>Specifies the sort order for columns in a query. Can be followed by either the Ascending or the Descending keyword. If neither is specified, Ascending is used.</value> </data> <data name="Specifies_the_statements_to_run_when_the_event_is_raised_by_the_RaiseEvent_statement_RaiseEvent_delegateSignature_End_RaiseEvent" xml:space="preserve"> <value>Specifies the statements to run when the event is raised by the RaiseEvent statement. RaiseEvent(&lt;delegateSignature&gt;)...End RaiseEvent</value> </data> <data name="Triggers_an_event_declared_at_module_level_within_a_class_form_or_document_RaiseEvent_eventName_bracket_argumentList_bracket" xml:space="preserve"> <value>Triggers an event declared at module level within a class, form, or document. RaiseEvent &lt;eventName&gt; [(&lt;argumentList&gt;)]</value> </data> <data name="Collapses_and_hides_sections_of_code_in_Visual_Basic_files" xml:space="preserve"> <value>Collapses and hides sections of code in Visual Basic files.</value> </data> <data name="Returns_execution_to_the_code_that_called_the_Function_Sub_Get_Set_or_Operator_procedure_Return_or_Return_expression" xml:space="preserve"> <value>Returns execution to the code that called the Function, Sub, Get, Set, or Operator procedure. Return -or- Return &lt;expression&gt;</value> </data> <data name="Runs_one_of_several_groups_of_statements_depending_on_the_value_of_an_expression" xml:space="preserve"> <value>Runs one of several groups of statements, depending on the value of an expression.</value> </data> <data name="Specifies_which_columns_to_include_in_the_result_of_a_query" xml:space="preserve"> <value>Specifies which columns to include in the result of a query.</value> </data> <data name="Skips_elements_up_to_a_specified_position_in_the_collection" xml:space="preserve"> <value>Skips elements up to a specified position in the collection.</value> </data> <data name="Specifies_how_much_to_increment_between_each_loop_iteration" xml:space="preserve"> <value>Specifies how much to increment between each loop iteration.</value> </data> <data name="Suspends_program_execution" xml:space="preserve"> <value>Suspends program execution.</value> </data> <data name="When_set_to_On_restricts_implicit_data_type_conversions_to_only_widening_conversions_Option_Strict_On_Off" xml:space="preserve"> <value>When set to On, restricts implicit data type conversions to only widening conversions. Option Strict {On | Off}</value> </data> <data name="Ensures_that_multiple_threads_do_not_execute_the_statement_block_at_the_same_time_SyncLock_object_End_Synclock" xml:space="preserve"> <value>Ensures that multiple threads do not execute the statement block at the same time. SyncLock &lt;object&gt;...End Synclock</value> </data> <data name="Includes_elements_up_to_a_specified_position_in_the_collection" xml:space="preserve"> <value>Includes elements up to a specified position in the collection.</value> </data> <data name="Sets_the_string_comparison_method_specified_in_Option_Compare_to_a_text_sort_order_that_is_not_case_sensitive" xml:space="preserve"> <value>Sets the string comparison method specified in Option Compare to a text sort order that is not case sensitive.</value> </data> <data name="Introduces_a_statement_block_to_be_compiled_or_executed_if_a_tested_condition_is_true" xml:space="preserve"> <value>Introduces a statement block to be compiled or executed if a tested condition is true.</value> </data> <data name="Throws_an_exception_within_a_procedure_so_that_you_can_handle_it_with_structured_or_unstructured_exception_handling_code" xml:space="preserve"> <value>Throws an exception within a procedure so that you can handle it with structured or unstructured exception-handling code.</value> </data> <data name="Represents_a_Boolean_value_that_passes_a_conditional_test" xml:space="preserve"> <value>Represents a Boolean value that passes a conditional test.</value> </data> <data name="Provides_a_way_to_handle_some_or_all_possible_errors_that_might_occur_in_a_given_block_of_code_while_still_running_the_code_Try_bracket_Catch_bracket_Catch_Finally_End_Try" xml:space="preserve"> <value>Provides a way to handle some or all possible errors that might occur in a given block of code, while still running the code. Try...[Catch]...{Catch | Finally}...End Try</value> </data> <data name="A_Using_block_does_three_things_colon_it_creates_and_initializes_variables_in_the_resource_list_it_runs_the_code_in_the_block_and_it_disposes_of_the_variables_before_exiting_Resources_used_in_the_Using_block_must_implement_System_IDisposable_Using_resource1_bracket_resource2_bracket_End_Using" xml:space="preserve"> <value>A Using block does three things: it creates and initializes variables in the resource list, it runs the code in the block, and it disposes of the variables before exiting. Resources used in the Using block must implement System.IDisposable. Using &lt;resource1&gt;[, &lt;resource2&gt;]...End Using</value> </data> <data name="Adds_a_conditional_test_to_a_Catch_statement_Exceptions_are_caught_by_that_Catch_statement_only_when_the_conditional_test_that_follows_the_When_keyword_evaluates_to_True" xml:space="preserve"> <value>Adds a conditional test to a Catch statement. Exceptions are caught by that Catch statement only when the conditional test that follows the When keyword evaluates to True.</value> </data> <data name="Specifies_the_filtering_condition_for_a_range_variable_in_a_query" xml:space="preserve"> <value>Specifies the filtering condition for a range variable in a query.</value> </data> <data name="Runs_a_series_of_statements_as_long_as_a_given_condition_is_true" xml:space="preserve"> <value>Runs a series of statements as long as a given condition is true.</value> </data> <data name="Specifies_a_condition_for_Skip_and_Take_operations_Elements_will_be_bypassed_or_included_as_long_as_the_condition_is_true" xml:space="preserve"> <value>Specifies a condition for Skip and Take operations. Elements will be bypassed or included as long as the condition is true.</value> </data> <data name="Specifies_the_declaration_of_property_initializations_in_an_object_initializer_New_typeName_With_bracket_property_expression_bracket_bracket_bracket" xml:space="preserve"> <value>Specifies the declaration of property initializations in an object initializer. New &lt;typeName&gt; With {[.&lt;property&gt; = &lt;expression&gt;][,...]}</value> </data> <data name="Runs_a_series_of_statements_that_refer_to_a_single_object_or_structure_With_object_End_With" xml:space="preserve"> <value>Runs a series of statements that refer to a single object or structure. With &lt;object&gt;...End With</value> </data> <data name="Produces_an_element_of_an_IEnumerable_or_IEnumerator" xml:space="preserve"> <value>Produces an element of an IEnumerable or IEnumerator.</value> </data> <data name="Defines_an_asynchronous_lambda_expression_that_can_use_the_Await_operator_Can_be_used_wherever_a_delegate_type_is_expected_Async_Sub_Function_parameterList_expression" xml:space="preserve"> <value>Defines an asynchronous lambda expression that can use the Await operator. Can be used wherever a delegate type is expected. Async Sub/Function(&lt;parameterList&gt;) &lt;expression&gt;</value> </data> <data name="Defines_a_lambda_expression_that_calculates_and_returns_a_single_value_Can_be_used_wherever_a_delegate_type_is_expected_Function_parameterList_expression" xml:space="preserve"> <value>Defines a lambda expression that calculates and returns a single value. Can be used wherever a delegate type is expected. Function(&lt;parameterList&gt;) &lt;expression&gt;</value> </data> <data name="Defines_a_lambda_expression_that_can_execute_statements_and_does_not_return_a_value_Can_be_used_wherever_a_delegate_type_is_expected_Sub_parameterList_statement" xml:space="preserve"> <value>Defines a lambda expression that can execute statements and does not return a value. Can be used wherever a delegate type is expected. Sub(&lt;parameterList&gt;) &lt;statement&gt;</value> </data> <data name="Disables_reporting_of_specified_warnings_in_the_portion_of_the_source_file_below_the_current_line" xml:space="preserve"> <value>Disables reporting of specified warnings in the portion of the source file below the current line.</value> </data> <data name="Enables_reporting_of_specified_warnings_in_the_portion_of_the_source_file_below_the_current_line" xml:space="preserve"> <value>Enables reporting of specified warnings in the portion of the source file below the current line.</value> </data> <data name="Insert_Await" xml:space="preserve"> <value>Insert 'Await'.</value> </data> <data name="Make_0_an_Async_Function" xml:space="preserve"> <value>Make {0} an Async Function.</value> </data> <data name="Convert_0_to_Iterator" xml:space="preserve"> <value>Convert {0} to Iterator</value> </data> <data name="Replace_Return_with_Yield" xml:space="preserve"> <value>Replace 'Return' with 'Yield</value> </data> <data name="Use_the_correct_control_variable" xml:space="preserve"> <value>Use the correct control variable</value> </data> <data name="NameOf_function" xml:space="preserve"> <value>NameOf function</value> </data> <data name="Generate_narrowing_conversion_in_0" xml:space="preserve"> <value>Generate narrowing conversion in '{0}'</value> </data> <data name="Generate_widening_conversion_in_0" xml:space="preserve"> <value>Generate widening conversion in '{0}'</value> </data> <data name="Try_block" xml:space="preserve"> <value>Try block</value> <comment>{Locked="Try"} "Try" is a VB keyword and should not be localized.</comment> </data> <data name="Catch_clause" xml:space="preserve"> <value>Catch clause</value> <comment>{Locked="Catch"} "Catch" is a VB keyword and should not be localized.</comment> </data> <data name="Finally_clause" xml:space="preserve"> <value>Finally clause</value> <comment>{Locked="Finally"} "Finally" is a VB keyword and should not be localized.</comment> </data> <data name="Using_statement" xml:space="preserve"> <value>Using statement</value> <comment>{Locked="Using"} "Using" is a VB keyword and should not be localized.</comment> </data> <data name="Using_block" xml:space="preserve"> <value>Using block</value> <comment>{Locked="Using"} "Using" is a VB keyword and should not be localized.</comment> </data> <data name="With_statement" xml:space="preserve"> <value>With statement</value> <comment>{Locked="With"} "With" is a VB keyword and should not be localized.</comment> </data> <data name="With_block" xml:space="preserve"> <value>With block</value> <comment>{Locked="With"} "With" is a VB keyword and should not be localized.</comment> </data> <data name="SyncLock_statement" xml:space="preserve"> <value>SyncLock statement</value> <comment>{Locked="SyncLock"} "SyncLock" is a VB keyword and should not be localized.</comment> </data> <data name="SyncLock_block" xml:space="preserve"> <value>SyncLock block</value> <comment>{Locked="SyncLock"} "SyncLock" is a VB keyword and should not be localized.</comment> </data> <data name="For_Each_statement" xml:space="preserve"> <value>For Each statement</value> <comment>{Locked="For Each"} "For Each" is a VB keyword and should not be localized.</comment> </data> <data name="For_Each_block" xml:space="preserve"> <value>For Each block</value> <comment>{Locked="For Each"} "For Each" is a VB keyword and should not be localized.</comment> </data> <data name="On_Error_statement" xml:space="preserve"> <value>On Error statement</value> <comment>{Locked="On Error"} "On Error" is a VB keyword and should not be localized.</comment> </data> <data name="Resume_statement" xml:space="preserve"> <value>Resume statement</value> <comment>{Locked="Resume"} "Resume" is a VB keyword and should not be localized.</comment> </data> <data name="Yield_statement" xml:space="preserve"> <value>Yield statement</value> <comment>{Locked="Yield"} "Yield" is a VB keyword and should not be localized.</comment> </data> <data name="Await_expression" xml:space="preserve"> <value>Await expression</value> <comment>{Locked="Await"} "Await" is a VB keyword and should not be localized.</comment> </data> <data name="Lambda" xml:space="preserve"> <value>Lambda</value> </data> <data name="Where_clause" xml:space="preserve"> <value>Where clause</value> <comment>{Locked="Where"} "Where" is a VB keyword and should not be localized.</comment> </data> <data name="Select_clause" xml:space="preserve"> <value>Select clause</value> <comment>{Locked="Select"} "Select" is a VB keyword and should not be localized.</comment> </data> <data name="From_clause" xml:space="preserve"> <value>From clause</value> <comment>{Locked="From"} "From" is a VB keyword and should not be localized.</comment> </data> <data name="Aggregate_clause" xml:space="preserve"> <value>Aggregate clause</value> <comment>{Locked="Aggregate"} "Aggregate" is a VB keyword and should not be localized.</comment> </data> <data name="Let_clause" xml:space="preserve"> <value>Let clause</value> <comment>{Locked="Let"} "Let" is a VB keyword and should not be localized.</comment> </data> <data name="Join_clause" xml:space="preserve"> <value>Join clause</value> <comment>{Locked="Join"} "Join" is a VB keyword and should not be localized.</comment> </data> <data name="Group_Join_clause" xml:space="preserve"> <value>Group Join clause</value> <comment>{Locked="Group Join"} "Group Join" is a VB keyword and should not be localized.</comment> </data> <data name="Group_By_clause" xml:space="preserve"> <value>Group By clause</value> <comment>{Locked="Group By"} "Group By" is a VB keyword and should not be localized.</comment> </data> <data name="Function_aggregation" xml:space="preserve"> <value>Function aggregation</value> </data> <data name="Take_While_clause" xml:space="preserve"> <value>Take While clause</value> <comment>{Locked="Take While"} "Take While" is a VB keyword and should not be localized.</comment> </data> <data name="Skip_While_clause" xml:space="preserve"> <value>Skip While clause</value> <comment>{Locked="Skip While"} "Skip While" is a VB keyword and should not be localized.</comment> </data> <data name="Ordering_clause" xml:space="preserve"> <value>Ordering clause</value> <comment>{Locked="Ordering"} "Ordering" is a VB keyword and should not be localized.</comment> </data> <data name="Join_condition" xml:space="preserve"> <value>Join condition</value> <comment>{Locked="Join"} "Join" is a VB keyword and should not be localized.</comment> </data> <data name="option_" xml:space="preserve"> <value>option</value> <comment>{Locked}</comment> </data> <data name="import" xml:space="preserve"> <value>import</value> <comment>{Locked}</comment> </data> <data name="structure_" xml:space="preserve"> <value>structure</value> <comment>{Locked}</comment> </data> <data name="module_" xml:space="preserve"> <value>module</value> <comment>{Locked}</comment> </data> <data name="WithEvents_field" xml:space="preserve"> <value>WithEvents field</value> <comment>{Locked="WithEvents"} "WithEvents" is a VB keyword and should not be localized.</comment> </data> <data name="as_clause" xml:space="preserve"> <value>as clause</value> <comment>{Locked="as"} "as" is a VB keyword and should not be localized.</comment> </data> <data name="type_parameters" xml:space="preserve"> <value>type parameters</value> </data> <data name="parameters" xml:space="preserve"> <value>parameters</value> </data> <data name="attributes" xml:space="preserve"> <value>attributes</value> </data> <data name="Too_many_arguments_to_0" xml:space="preserve"> <value>Too many arguments to '{0}'.</value> </data> <data name="Type_0_is_not_defined" xml:space="preserve"> <value>Type '{0}' is not defined.</value> </data> <data name="Add_Overloads" xml:space="preserve"> <value>Add 'Overloads'</value> <comment>{Locked="Overloads"} "Overloads" is a VB keyword and should not be localized.</comment> </data> <data name="Add_a_metadata_reference_to_specified_assembly_and_all_its_dependencies_e_g_Sharpr_myLib_dll" xml:space="preserve"> <value>Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll".</value> </data> <data name="Properties" xml:space="preserve"> <value>Properties</value> </data> <data name="namespace_name" xml:space="preserve"> <value>&lt;namespace name&gt;</value> </data> <data name="Type_a_name_here_to_declare_a_namespace" xml:space="preserve"> <value>Type a name here to declare a namespace.</value> </data> <data name="Type_a_name_here_to_declare_a_partial_class" xml:space="preserve"> <value>Type a name here to declare a partial class.</value> </data> <data name="class_name" xml:space="preserve"> <value>&lt;class name&gt;</value> </data> <data name="interface_name" xml:space="preserve"> <value>&lt;interface name&gt;</value> </data> <data name="module_name" xml:space="preserve"> <value>&lt;module name&gt;</value> </data> <data name="structure_name" xml:space="preserve"> <value>&lt;structure name&gt;</value> </data> <data name="Type_a_name_here_to_declare_a_partial_interface" xml:space="preserve"> <value>Type a name here to declare a partial interface.</value> </data> <data name="Type_a_name_here_to_declare_a_partial_module" xml:space="preserve"> <value>Type a name here to declare a partial module.</value> </data> <data name="Type_a_name_here_to_declare_a_partial_structure" xml:space="preserve"> <value>Type a name here to declare a partial structure.</value> </data> <data name="Event_add_handler_name" xml:space="preserve"> <value>{0}.add</value> <comment>The name of an event add handler where "{0}" is the event name.</comment> </data> <data name="Event_remove_handler_name" xml:space="preserve"> <value>{0}.remove</value> <comment>The name of an event remove handler where "{0}" is the event name.</comment> </data> <data name="Property_getter_name" xml:space="preserve"> <value>{0}.get</value> <comment>The name of a property getter like "public int MyProperty { get; }" where "{0}" is the property name</comment> </data> <data name="Property_setter_name" xml:space="preserve"> <value>{0}.set</value> <comment>The name of a property setter like "public int MyProperty { set; }" where "{0}" is the property name</comment> </data> <data name="Make_Async_Function" xml:space="preserve"> <value>Make Async Function</value> </data> <data name="Make_Async_Sub" xml:space="preserve"> <value>Make Async Sub</value> </data> <data name="Multiple_Types" xml:space="preserve"> <value>&lt;Multiple Types&gt;</value> </data> <data name="Convert_to_Select_Case" xml:space="preserve"> <value>Convert to 'Select Case'</value> </data> <data name="Convert_to_For_Each" xml:space="preserve"> <value>Convert to 'For Each'</value> </data> <data name="Convert_to_For" xml:space="preserve"> <value>Convert to 'For'</value> </data> <data name="Add_Obsolete" xml:space="preserve"> <value>Add &lt;Obsolete&gt;</value> </data> <data name="Add_missing_Imports" xml:space="preserve"> <value>Add missing Imports</value> <comment>{Locked="Import"}</comment> </data> <data name="Add_Shadows" xml:space="preserve"> <value>Add 'Shadows'</value> <comment>{Locked="Shadows"} "Shadows" is a VB keyword and should not be localized.</comment> </data> <data name="Introduce_Using_statement" xml:space="preserve"> <value>Introduce 'Using' statement</value> <comment>{Locked="Using"} "Using" is a VB keyword and should not be localized.</comment> </data> <data name="Make_0_inheritable" xml:space="preserve"> <value>Make '{0}' inheritable</value> </data> <data name="Apply_Me_qualification_preferences" xml:space="preserve"> <value>Apply Me qualification preferences</value> <comment>{Locked="Me"} "Me" is a VB keyword and should not be localized.</comment> </data> <data name="Apply_Imports_directive_placement_preferences" xml:space="preserve"> <value>Apply Imports directive placement preferences</value> <comment>{Locked="Import"} "Import" is a VB keyword and should not be localized.</comment> </data> <data name="Make_private_field_ReadOnly_when_possible" xml:space="preserve"> <value>Make private field ReadOnly when possible</value> <comment>{Locked="ReadOnly"} "ReadOnly" is a VB keyword and should not be localized.</comment> </data> <data name="Organize_Imports" xml:space="preserve"> <value>Organize Imports</value> <comment>{Locked="Import"}</comment> </data> <data name="Change_to_DirectCast" xml:space="preserve"> <value>Change to 'DirectCast'</value> </data> <data name="Change_to_TryCast" xml:space="preserve"> <value>Change to 'TryCast'</value> </data> <data name="Remove_shared_keyword_from_module_member" xml:space="preserve"> <value>Remove 'Shared' keyword from Module member</value> <comment>{Locked="Shared"} "Shared" is a VB keyword and should not be localized.</comment> </data> <data name="_0_Events" xml:space="preserve"> <value>({0} Events)</value> </data> <data name="Shared_constructor" xml:space="preserve"> <value>Shared constructor</value> </data> </root>
<?xml version="1.0" encoding="utf-8"?> <root> <!-- Microsoft ResX Schema Version 2.0 The primary goals of this format is to allow a simple XML format that is mostly human readable. The generation and parsing of the various data types are done through the TypeConverter classes associated with the data types. Example: ... ado.net/XML headers & schema ... <resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="version">2.0</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> <value>[base64 mime encoded serialized .NET Framework object]</value> </data> <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <comment>This is a comment</comment> </data> There are any number of "resheader" rows that contain simple name/value pairs. Each data row contains a name, and value. The row also contains a type or mimetype. Type corresponds to a .NET class that support text/value conversion through the TypeConverter architecture. Classes that don't support this are serialized and stored with the mimetype set. The mimetype is used for serialized objects, and tells the ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly: Note - application/x-microsoft.net.object.binary.base64 is the format that the ResXResourceWriter will generate, however the reader can read any of the formats listed below. mimetype: application/x-microsoft.net.object.binary.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.soap.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.bytearray.base64 value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:import namespace="http://www.w3.org/XML/1998/namespace" /> <xsd:element name="root" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="metadata"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" /> </xsd:sequence> <xsd:attribute name="name" use="required" type="xsd:string" /> <xsd:attribute name="type" type="xsd:string" /> <xsd:attribute name="mimetype" type="xsd:string" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="assembly"> <xsd:complexType> <xsd:attribute name="alias" type="xsd:string" /> <xsd:attribute name="name" type="xsd:string" /> </xsd:complexType> </xsd:element> <xsd:element name="data"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> <xsd:attribute ref="xml:space" /> </xsd:complexType> </xsd:element> <xsd:element name="resheader"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <resheader name="version"> <value>2.0</value> </resheader> <resheader name="reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <data name="Insert_0" xml:space="preserve"> <value>Insert '{0}'.</value> </data> <data name="Delete_the_0_statement1" xml:space="preserve"> <value>Delete the '{0}' statement.</value> </data> <data name="Create_event_0_in_1" xml:space="preserve"> <value>Create event {0} in {1}</value> </data> <data name="Insert_the_missing_End_Property_statement" xml:space="preserve"> <value>Insert the missing 'End Property' statement.</value> </data> <data name="Insert_the_missing_0" xml:space="preserve"> <value>Insert the missing '{0}'.</value> </data> <data name="Inline_temporary_variable" xml:space="preserve"> <value>Inline temporary variable</value> </data> <data name="Conflict_s_detected" xml:space="preserve"> <value>Conflict(s) detected.</value> </data> <data name="Invert_If" xml:space="preserve"> <value>Invert If</value> </data> <data name="Add_Await" xml:space="preserve"> <value>Add Await</value> </data> <data name="Add_Await_and_ConfigureAwaitFalse" xml:space="preserve"> <value>Add Await and 'ConfigureAwait(false)'</value> </data> <data name="Move_the_0_statement_to_line_1" xml:space="preserve"> <value>Move the '{0}' statement to line {1}.</value> </data> <data name="Delete_the_0_statement2" xml:space="preserve"> <value>Delete the '{0}' statement.</value> </data> <data name="Type_a_name_here_to_declare_a_new_field" xml:space="preserve"> <value>Type a name here to declare a new field.</value> </data> <data name="Note_colon_Space_completion_is_disabled_to_avoid_potential_interference_To_insert_a_name_from_the_list_use_tab" xml:space="preserve"> <value>Note: Space completion is disabled to avoid potential interference. To insert a name from the list, use tab.</value> </data> <data name="new_field" xml:space="preserve"> <value>&lt;new field&gt;</value> </data> <data name="Type_a_name_here_to_declare_a_parameter_If_no_preceding_keyword_is_used_ByVal_will_be_assumed_and_the_argument_will_be_passed_by_value" xml:space="preserve"> <value>Type a name here to declare a parameter. If no preceding keyword is used; 'ByVal' will be assumed and the argument will be passed by value.</value> </data> <data name="parameter_name" xml:space="preserve"> <value>&lt;parameter name&gt;</value> </data> <data name="Type_a_new_name_for_the_column_followed_by_Otherwise_the_original_column_name_with_be_used" xml:space="preserve"> <value>Type a new name for the column, followed by '='. Otherwise, the original column name with be used.</value> </data> <data name="Note_colon_Use_tab_for_automatic_completion_space_completion_is_disabled_to_avoid_interfering_with_a_new_name" xml:space="preserve"> <value>Note: Use tab for automatic completion; space completion is disabled to avoid interfering with a new name.</value> </data> <data name="result_alias" xml:space="preserve"> <value>&lt;result alias&gt;</value> </data> <data name="Type_a_new_variable_name" xml:space="preserve"> <value>Type a new variable name</value> </data> <data name="Note_colon_Space_and_completion_are_disabled_to_avoid_potential_interference_To_insert_a_name_from_the_list_use_tab" xml:space="preserve"> <value>Note: Space and '=' completion are disabled to avoid potential interference. To insert a name from the list, use tab.</value> </data> <data name="new_resource" xml:space="preserve"> <value>&lt;new resource&gt;</value> </data> <data name="AddHandler_statement" xml:space="preserve"> <value>AddHandler statement</value> </data> <data name="RemoveHandler_statement" xml:space="preserve"> <value>RemoveHandler statement</value> </data> <data name="_0_function" xml:space="preserve"> <value>{0} function</value> </data> <data name="CType_function" xml:space="preserve"> <value>CType function</value> </data> <data name="DirectCast_function" xml:space="preserve"> <value>DirectCast function</value> </data> <data name="TryCast_function" xml:space="preserve"> <value>TryCast function</value> </data> <data name="GetType_function" xml:space="preserve"> <value>GetType function</value> </data> <data name="GetXmlNamespace_function" xml:space="preserve"> <value>GetXmlNamespace function</value> </data> <data name="Mid_statement" xml:space="preserve"> <value>Mid statement</value> </data> <data name="Fix_Incorrect_Function_Return_Type" xml:space="preserve"> <value>Fix Incorrect Function Return Type</value> </data> <data name="Simplify_name_0" xml:space="preserve"> <value>Simplify name '{0}'</value> </data> <data name="Simplify_member_access_0" xml:space="preserve"> <value>Simplify member access '{0}'</value> </data> <data name="Remove_Me_qualification" xml:space="preserve"> <value>Remove 'Me' qualification</value> <comment>{Locked="Me"} "Me" is a VB keyword and should not be localized.</comment> </data> <data name="Name_can_be_simplified" xml:space="preserve"> <value>Name can be simplified</value> </data> <data name="can_t_determine_valid_range_of_statements_to_extract_out" xml:space="preserve"> <value>can't determine valid range of statements to extract out</value> </data> <data name="Not_all_code_paths_return" xml:space="preserve"> <value>Not all code paths return</value> </data> <data name="contains_invalid_selection" xml:space="preserve"> <value>contains invalid selection</value> </data> <data name="the_selection_contains_syntactic_errors" xml:space="preserve"> <value>the selection contains syntactic errors</value> </data> <data name="Selection_can_t_be_crossed_over_preprocessors" xml:space="preserve"> <value>Selection can't be crossed over preprocessors</value> </data> <data name="Selection_can_t_contain_throw_without_enclosing_catch_block" xml:space="preserve"> <value>Selection can't contain throw without enclosing catch block</value> </data> <data name="Selection_can_t_be_parts_of_constant_initializer_expression" xml:space="preserve"> <value>Selection can't be parts of constant initializer expression</value> </data> <data name="Argument_used_for_ByRef_parameter_can_t_be_extracted_out" xml:space="preserve"> <value>Argument used for ByRef parameter can't be extracted out</value> </data> <data name="all_static_local_usages_defined_in_the_selection_must_be_included_in_the_selection" xml:space="preserve"> <value>all static local usages defined in the selection must be included in the selection</value> </data> <data name="Implicit_member_access_can_t_be_included_in_the_selection_without_containing_statement" xml:space="preserve"> <value>Implicit member access can't be included in the selection without containing statement</value> </data> <data name="Selection_must_be_part_of_executable_statements" xml:space="preserve"> <value>Selection must be part of executable statements</value> </data> <data name="next_statement_control_variable_doesn_t_have_matching_declaration_statement" xml:space="preserve"> <value>next statement control variable doesn't have matching declaration statement</value> </data> <data name="Selection_doesn_t_contain_any_valid_node" xml:space="preserve"> <value>Selection doesn't contain any valid node</value> </data> <data name="no_valid_statement_range_to_extract_out" xml:space="preserve"> <value>no valid statement range to extract out</value> </data> <data name="Invalid_selection" xml:space="preserve"> <value>Invalid selection</value> </data> <data name="Selection_doesn_t_contain_any_valid_token" xml:space="preserve"> <value>Selection doesn't contain any valid token</value> </data> <data name="No_valid_selection_to_perform_extraction" xml:space="preserve"> <value>No valid selection to perform extraction</value> </data> <data name="No_common_root_node_for_extraction" xml:space="preserve"> <value>No common root node for extraction</value> </data> <data name="Deprecated" xml:space="preserve"> <value>Deprecated</value> </data> <data name="Extension" xml:space="preserve"> <value>Extension</value> </data> <data name="Awaitable" xml:space="preserve"> <value>Awaitable</value> </data> <data name="Awaitable_Extension" xml:space="preserve"> <value>Awaitable, Extension</value> </data> <data name="new_variable" xml:space="preserve"> <value>&lt;new variable&gt;</value> </data> <data name="Creates_a_delegate_procedure_instance_that_references_the_specified_procedure_AddressOf_procedureName" xml:space="preserve"> <value>Creates a delegate procedure instance that references the specified procedure. AddressOf &lt;procedureName&gt;</value> </data> <data name="Indicates_that_an_external_procedure_has_another_name_in_its_DLL" xml:space="preserve"> <value>Indicates that an external procedure has another name in its DLL.</value> </data> <data name="Performs_a_short_circuit_logical_conjunction_on_two_expressions_Returns_True_if_both_operands_evaluate_to_True_If_the_first_expression_evaluates_to_False_the_second_is_not_evaluated_result_expression1_AndAlso_expression2" xml:space="preserve"> <value>Performs a short-circuit logical conjunction on two expressions. Returns True if both operands evaluate to True. If the first expression evaluates to False, the second is not evaluated. &lt;result&gt; = &lt;expression1&gt; AndAlso &lt;expression2&gt;</value> </data> <data name="Performs_a_logical_conjunction_on_two_Boolean_expressions_or_a_bitwise_conjunction_on_two_numeric_expressions_For_Boolean_expressions_returns_True_if_both_operands_evaluate_to_True_Both_expressions_are_always_evaluated_result_expression1_And_expression2" xml:space="preserve"> <value>Performs a logical conjunction on two Boolean expressions, or a bitwise conjunction on two numeric expressions. For Boolean expressions, returns True if both operands evaluate to True. Both expressions are always evaluated. &lt;result&gt; = &lt;expression1&gt; And &lt;expression2&gt;</value> </data> <data name="Used_in_a_Declare_statement_The_Ansi_modifier_specifies_that_Visual_Basic_should_marshal_all_strings_to_ANSI_values_and_should_look_up_the_procedure_without_modifying_its_name_during_the_search_If_no_character_set_is_specified_ANSI_is_the_default" xml:space="preserve"> <value>Used in a Declare statement. The Ansi modifier specifies that Visual Basic should marshal all strings to ANSI values, and should look up the procedure without modifying its name during the search. If no character set is specified, ANSI is the default.</value> </data> <data name="Specifies_a_data_type_in_a_declaration_statement" xml:space="preserve"> <value>Specifies a data type in a declaration statement.</value> </data> <data name="Specifies_that_an_attribute_at_the_beginning_of_a_source_file_applies_to_the_entire_assembly_Otherwise_the_attribute_will_apply_only_to_an_individual_programming_element_such_as_a_class_or_property" xml:space="preserve"> <value>Specifies that an attribute at the beginning of a source file applies to the entire assembly. Otherwise the attribute will apply only to an individual programming element, such as a class or property.</value> </data> <data name="Indicates_an_asynchronous_method_that_can_use_the_Await_operator" xml:space="preserve"> <value>Indicates an asynchronous method that can use the Await operator.</value> </data> <data name="Used_in_a_Declare_statement_The_Auto_modifier_specifies_that_Visual_Basic_should_marshal_strings_according_to_NET_Framework_rules_and_should_determine_the_base_character_set_of_the_run_time_platform_and_possibly_modify_the_external_procedure_name_if_the_initial_search_fails" xml:space="preserve"> <value>Used in a Declare statement. The Auto modifier specifies that Visual Basic should marshal strings according to .NET Framework rules, and should determine the base character set of the run-time platform and possibly modify the external procedure name if the initial search fails.</value> </data> <data name="Specifies_that_an_argument_is_passed_in_such_a_way_that_the_called_procedure_can_change_the_underlying_value_of_the_argument_in_the_calling_code" xml:space="preserve"> <value>Specifies that an argument is passed in such a way that the called procedure can change the underlying value of the argument in the calling code.</value> </data> <data name="Specifies_that_an_argument_is_passed_in_such_a_way_that_the_called_procedure_or_property_cannot_change_the_underlying_value_of_the_argument_in_the_calling_code" xml:space="preserve"> <value>Specifies that an argument is passed in such a way that the called procedure or property cannot change the underlying value of the argument in the calling code.</value> </data> <data name="Declares_the_name_of_a_class_and_introduces_the_definitions_of_the_variables_properties_and_methods_that_make_up_the_class" xml:space="preserve"> <value>Declares the name of a class and introduces the definitions of the variables, properties, and methods that make up the class.</value> </data> <data name="Generates_a_string_concatenation_of_two_expressions" xml:space="preserve"> <value>Generates a string concatenation of two expressions.</value> </data> <data name="Declares_and_defines_one_or_more_constants" xml:space="preserve"> <value>Declares and defines one or more constants.</value> </data> <data name="Use_In_for_a_type_that_will_only_be_used_for_ByVal_arguments_to_functions" xml:space="preserve"> <value>Use 'In' for a type that will only be used for ByVal arguments to functions.</value> </data> <data name="Use_Out_for_a_type_that_will_only_be_used_as_a_return_from_functions" xml:space="preserve"> <value>Use 'Out' for a type that will only be used as a return from functions.</value> </data> <data name="Returns_the_result_of_explicitly_converting_an_expression_to_a_specified_data_type_object_structure_class_or_interface_CType_Object_As_Expression_Object_As_Type_As_Type" xml:space="preserve"> <value>Returns the result of explicitly converting an expression to a specified data type, object, structure, class, or interface. CType(Object As Expression, Object As Type) As Type</value> </data> <data name="Specifies_that_an_event_has_additional_specialized_code_for_adding_handlers_removing_handlers_and_raising_events" xml:space="preserve"> <value>Specifies that an event has additional, specialized code for adding handlers, removing handlers, and raising events.</value> </data> <data name="Declares_a_reference_to_a_procedure_implemented_in_an_external_file" xml:space="preserve"> <value>Declares a reference to a procedure implemented in an external file.</value> </data> <data name="Identifies_a_property_as_the_default_property_of_its_class_structure_or_interface" xml:space="preserve"> <value>Identifies a property as the default property of its class, structure, or interface.</value> </data> <data name="Used_to_declare_a_delegate_A_delegate_is_a_reference_type_that_refers_to_a_shared_method_of_a_type_or_to_an_instance_method_of_an_object_Any_procedure_that_is_convertible_or_that_has_matching_parameter_types_and_return_type_may_be_used_to_create_an_instance_of_this_delegate_class" xml:space="preserve"> <value>Used to declare a delegate. A delegate is a reference type that refers to a shared method of a type or to an instance method of an object. Any procedure that is convertible, or that has matching parameter types and return type may be used to create an instance of this delegate class.</value> </data> <data name="Declares_and_allocates_storage_space_for_one_or_more_variables_Dim_var_bracket_As_bracket_New_bracket_dataType_bracket_boundList_bracket_bracket_bracket_initializer_bracket_bracket_var2_bracket" xml:space="preserve"> <value>Declares and allocates storage space for one or more variables. Dim {&lt;var&gt; [As [New] dataType [(boundList)]][= initializer]}[, var2]</value> </data> <data name="Divides_two_numbers_and_returns_a_floating_point_result" xml:space="preserve"> <value>Divides two numbers and returns a floating-point result.</value> </data> <data name="Terminates_a_0_block" xml:space="preserve"> <value>Terminates a {0} block.</value> </data> <data name="Terminates_an_0_block" xml:space="preserve"> <value>Terminates an {0} block.</value> </data> <data name="Terminates_the_definition_of_a_0_statement" xml:space="preserve"> <value>Terminates the definition of a {0} statement.</value> </data> <data name="Terminates_the_definition_of_an_0_statement" xml:space="preserve"> <value>Terminates the definition of an {0} statement.</value> </data> <data name="Declares_an_enumeration_and_defines_the_values_of_its_members" xml:space="preserve"> <value>Declares an enumeration and defines the values of its members.</value> </data> <data name="Compares_two_expressions_and_returns_True_if_they_are_equal_Otherwise_returns_False" xml:space="preserve"> <value>Compares two expressions and returns True if they are equal. Otherwise, returns False.</value> </data> <data name="Used_to_release_array_variables_and_deallocate_the_memory_used_for_their_elements" xml:space="preserve"> <value>Used to release array variables and deallocate the memory used for their elements.</value> </data> <data name="Declares_a_user_defined_event" xml:space="preserve"> <value>Declares a user-defined event.</value> </data> <data name="Exits_a_Sub_procedure_and_transfers_execution_immediately_to_the_statement_following_the_call_to_the_Sub_procedure" xml:space="preserve"> <value>Exits a Sub procedure and transfers execution immediately to the statement following the call to the Sub procedure.</value> </data> <data name="Raises_a_number_to_the_power_of_another_number" xml:space="preserve"> <value>Raises a number to the power of another number.</value> </data> <data name="Specifies_that_the_external_procedure_being_referenced_in_the_Declare_statement_is_a_Function" xml:space="preserve"> <value>Specifies that the external procedure being referenced in the Declare statement is a Function.</value> </data> <data name="Specifies_that_the_external_procedure_being_referenced_in_the_Declare_statement_is_a_Sub" xml:space="preserve"> <value>Specifies that the external procedure being referenced in the Declare statement is a Sub.</value> </data> <data name="Specifies_that_one_or_more_declared_programming_elements_are_accessible_only_from_within_the_assembly_that_contains_their_declaration" xml:space="preserve"> <value>Specifies that one or more declared programming elements are accessible only from within the assembly that contains their declaration.</value> </data> <data name="Specifies_a_collection_and_a_range_variable_to_use_in_a_query" xml:space="preserve"> <value>Specifies a collection and a range variable to use in a query.</value> </data> <data name="Declares_the_name_parameters_and_code_that_define_a_Function_procedure_that_is_a_procedure_that_returns_a_value_to_the_calling_code" xml:space="preserve"> <value>Declares the name, parameters, and code that define a Function procedure, that is, a procedure that returns a value to the calling code.</value> </data> <data name="Constrains_a_generic_type_parameter_to_require_that_any_type_argument_passed_to_it_be_a_reference_type" xml:space="preserve"> <value>Constrains a generic type parameter to require that any type argument passed to it be a reference type.</value> </data> <data name="Specifies_a_constructor_constraint_on_a_generic_type_parameter" xml:space="preserve"> <value>Specifies a constructor constraint on a generic type parameter.</value> </data> <data name="Constrains_a_generic_type_parameter_to_require_that_any_type_argument_passed_to_it_be_a_value_type" xml:space="preserve"> <value>Constrains a generic type parameter to require that any type argument passed to it be a value type.</value> </data> <data name="Declares_a_Get_property_procedure_that_is_used_to_return_the_current_value_of_a_property" xml:space="preserve"> <value>Declares a Get property procedure that is used to return the current value of a property.</value> </data> <data name="Compares_two_expressions_and_returns_True_if_the_first_is_greater_than_the_second_Otherwise_returns_False" xml:space="preserve"> <value>Compares two expressions and returns True if the first is greater than the second. Otherwise, returns False.</value> </data> <data name="Compares_two_expressions_and_returns_True_if_the_first_is_greater_than_or_equal_to_the_second_Otherwise_returns_False" xml:space="preserve"> <value>Compares two expressions and returns True if the first is greater than or equal to the second. Otherwise, returns False.</value> </data> <data name="Declares_that_a_procedure_handles_a_specified_event" xml:space="preserve"> <value>Declares that a procedure handles a specified event.</value> </data> <data name="Indicates_that_a_class_or_structure_member_is_providing_the_implementation_for_a_member_defined_in_an_interface" xml:space="preserve"> <value>Indicates that a class or structure member is providing the implementation for a member defined in an interface.</value> </data> <data name="Specifies_one_or_more_interfaces_or_interface_members_that_must_be_implemented_in_the_class_or_structure_definition_in_which_the_Implements_statement_appears" xml:space="preserve"> <value>Specifies one or more interfaces, or interface members, that must be implemented in the class or structure definition in which the Implements statement appears.</value> </data> <data name="Imports_all_or_specified_elements_of_a_namespace_into_a_file" xml:space="preserve"> <value>Imports all or specified elements of a namespace into a file.</value> </data> <data name="Specifies_the_group_that_the_loop_variable_in_a_For_Each_statement_is_to_traverse" xml:space="preserve"> <value>Specifies the group that the loop variable in a For Each statement is to traverse.</value> </data> <data name="Specifies_the_group_that_the_loop_variable_is_to_traverse_in_a_For_Each_statement_or_specifies_the_range_variable_in_a_query" xml:space="preserve"> <value>Specifies the group that the loop variable is to traverse in a For Each statement, or specifies the range variable in a query.</value> </data> <data name="Causes_the_current_class_or_interface_to_inherit_the_attributes_variables_properties_procedures_and_events_from_another_class_or_set_of_interfaces" xml:space="preserve"> <value>Causes the current class or interface to inherit the attributes, variables, properties, procedures, and events from another class or set of interfaces.</value> </data> <data name="Specifies_the_group_that_the_range_variable_is_to_traverse_in_a_query" xml:space="preserve"> <value>Specifies the group that the range variable is to traverse in a query.</value> </data> <data name="Divides_two_numbers_and_returns_an_integer_result" xml:space="preserve"> <value>Divides two numbers and returns an integer result.</value> </data> <data name="Declares_the_name_of_an_interface_and_the_definitions_of_the_members_of_the_interface" xml:space="preserve"> <value>Declares the name of an interface and the definitions of the members of the interface.</value> </data> <data name="Determines_whether_an_expression_is_false_If_instances_of_any_class_or_structure_will_be_used_in_an_OrElse_clause_you_must_define_IsFalse_on_that_class_or_structure" xml:space="preserve"> <value>Determines whether an expression is false. If instances of any class or structure will be used in an OrElse clause, you must define IsFalse on that class or structure.</value> </data> <data name="Compares_two_object_reference_variables_and_returns_True_if_the_objects_are_equal_result_object1_Is_object2" xml:space="preserve"> <value>Compares two object reference variables and returns True if the objects are equal. &lt;result&gt; = &lt;object1&gt; Is &lt;object2&gt;</value> </data> <data name="Compares_two_object_reference_variables_and_returns_True_if_the_objects_are_not_equal_result_object1_IsNot_object2" xml:space="preserve"> <value>Compares two object reference variables and returns True if the objects are not equal. &lt;result&gt; = &lt;object1&gt; IsNot &lt;object2&gt;</value> </data> <data name="Determines_whether_an_expression_is_true_If_instances_of_any_class_or_structure_will_be_used_in_an_OrElse_clause_you_must_define_IsTrue_on_that_class_or_structure" xml:space="preserve"> <value>Determines whether an expression is true. If instances of any class or structure will be used in an OrElse clause, you must define IsTrue on that class or structure.</value> </data> <data name="Indicates_an_iterator_method_that_can_use_the_Yield_statement" xml:space="preserve"> <value>Indicates an iterator method that can use the Yield statement.</value> </data> <data name="Defines_an_iterator_lambda_expression_that_can_use_the_Yield_statement_Iterator_Function_parameterList_As_IEnumerable_Of_T" xml:space="preserve"> <value>Defines an iterator lambda expression that can use the Yield statement. Iterator Function(&lt;parameterList&gt;) As IEnumerable(Of &lt;T&gt;)</value> </data> <data name="Performs_an_arithmetic_left_shift_on_a_bit_pattern" xml:space="preserve"> <value>Performs an arithmetic left shift on a bit pattern.</value> </data> <data name="Compares_two_expressions_and_returns_True_if_the_first_is_less_than_the_second_Otherwise_returns_False" xml:space="preserve"> <value>Compares two expressions and returns True if the first is less than the second. Otherwise, returns False.</value> </data> <data name="Compares_two_expressions_and_returns_True_if_the_first_is_less_than_or_equal_to_the_second_Otherwise_returns_False" xml:space="preserve"> <value>Compares two expressions and returns True if the first is less than or equal to the second. Otherwise, returns False.</value> </data> <data name="Introduces_a_clause_that_identifies_the_external_file_DLL_or_code_resource_containing_an_external_procedure" xml:space="preserve"> <value>Introduces a clause that identifies the external file (DLL or code resource) containing an external procedure.</value> </data> <data name="Compares_a_string_against_a_pattern_Wildcards_available_include_to_match_1_character_and_to_match_0_or_more_characters_result_string_Like_pattern" xml:space="preserve"> <value>Compares a string against a pattern. Wildcards available include ? to match 1 character and * to match 0 or more characters. &lt;result&gt; = &lt;string&gt; Like &lt;pattern&gt;</value> </data> <data name="Returns_the_difference_between_two_numeric_expressions_or_the_negative_value_of_a_numeric_expression" xml:space="preserve"> <value>Returns the difference between two numeric expressions, or the negative value of a numeric expression.</value> </data> <data name="Divides_two_numbers_and_returns_only_the_remainder_number1_Mod_number2" xml:space="preserve"> <value>Divides two numbers and returns only the remainder. &lt;number1&gt; Mod &lt;number2&gt;</value> </data> <data name="Specifies_that_an_attribute_at_the_beginning_of_a_source_file_applies_to_the_entire_module_Otherwise_the_attribute_will_apply_only_to_an_individual_programming_element_such_as_a_class_or_property" xml:space="preserve"> <value>Specifies that an attribute at the beginning of a source file applies to the entire module. Otherwise the attribute will apply only to an individual programming element, such as a class or property.</value> </data> <data name="Multiplies_two_numbers_and_returns_the_product" xml:space="preserve"> <value>Multiplies two numbers and returns the product.</value> </data> <data name="Specifies_that_a_class_can_be_used_only_as_a_base_class_and_that_you_cannot_create_an_object_directly_from_it" xml:space="preserve"> <value>Specifies that a class can be used only as a base class, and that you cannot create an object directly from it.</value> </data> <data name="Specifies_that_a_property_or_procedure_is_not_implemented_in_the_class_and_must_be_overridden_in_a_derived_class_before_it_can_be_used" xml:space="preserve"> <value>Specifies that a property or procedure is not implemented in the class and must be overridden in a derived class before it can be used.</value> </data> <data name="Declares_the_name_of_a_namespace_and_causes_the_source_code_following_the_declaration_to_be_compiled_within_that_namespace" xml:space="preserve"> <value>Declares the name of a namespace, and causes the source code following the declaration to be compiled within that namespace.</value> </data> <data name="Indicates_that_a_conversion_operator_CType_converts_a_class_or_structure_to_a_type_that_might_not_be_able_to_hold_some_of_the_possible_values_of_the_original_class_or_structure" xml:space="preserve"> <value>Indicates that a conversion operator (CType) converts a class or structure to a type that might not be able to hold some of the possible values of the original class or structure.</value> </data> <data name="Compares_two_expressions_and_returns_True_if_they_are_not_equal_Otherwise_returns_False" xml:space="preserve"> <value>Compares two expressions and returns True if they are not equal. Otherwise, returns False.</value> </data> <data name="Specifies_that_a_class_cannot_be_used_as_a_base_class" xml:space="preserve"> <value>Specifies that a class cannot be used as a base class.</value> </data> <data name="Performs_logical_negation_on_a_Boolean_expression_or_bitwise_negation_on_a_numeric_expression_result_Not_expression" xml:space="preserve"> <value>Performs logical negation on a Boolean expression, or bitwise negation on a numeric expression. &lt;result&gt; = Not &lt;expression&gt;</value> </data> <data name="Specifies_that_a_property_or_procedure_cannot_be_overridden_in_a_derived_class" xml:space="preserve"> <value>Specifies that a property or procedure cannot be overridden in a derived class.</value> </data> <data name="Identifies_a_type_parameter_on_a_generic_class_structure_interface_delegate_or_procedure" xml:space="preserve"> <value>Identifies a type parameter on a generic class, structure, interface, delegate, or procedure.</value> </data> <data name="Declares_the_operator_symbol_operands_and_code_that_define_an_operator_procedure_on_a_class_or_structure" xml:space="preserve"> <value>Declares the operator symbol, operands, and code that define an operator procedure on a class or structure.</value> </data> <data name="Specifies_that_a_procedure_argument_can_be_omitted_when_the_procedure_is_called" xml:space="preserve"> <value>Specifies that a procedure argument can be omitted when the procedure is called.</value> </data> <data name="Introduces_a_statement_that_specifies_a_compiler_option_that_applies_to_the_entire_source_file" xml:space="preserve"> <value>Introduces a statement that specifies a compiler option that applies to the entire source file.</value> </data> <data name="Performs_short_circuit_inclusive_logical_disjunction_on_two_expressions_Returns_True_if_either_operand_evaluates_to_True_If_the_first_expression_evaluates_to_True_the_second_expression_is_not_evaluated_result_expression1_OrElse_expression2" xml:space="preserve"> <value>Performs short-circuit inclusive logical disjunction on two expressions. Returns True if either operand evaluates to True. If the first expression evaluates to True, the second expression is not evaluated. &lt;result&gt; = &lt;expression1&gt; OrElse &lt;expression2&gt;</value> </data> <data name="Performs_an_inclusive_logical_disjunction_on_two_Boolean_expressions_or_a_bitwise_disjunction_on_two_numeric_expressions_For_Boolean_expressions_returns_True_if_at_least_one_operand_evaluates_to_True_Both_expressions_are_always_evaluated_result_expression1_Or_expression2" xml:space="preserve"> <value>Performs an inclusive logical disjunction on two Boolean expressions, or a bitwise disjunction on two numeric expressions. For Boolean expressions, returns True if at least one operand evaluates to True. Both expressions are always evaluated. &lt;result&gt; = &lt;expression1&gt; Or &lt;expression2&gt;</value> </data> <data name="Specifies_that_a_property_or_procedure_re_declares_one_or_more_existing_properties_or_procedures_with_the_same_name" xml:space="preserve"> <value>Specifies that a property or procedure re-declares one or more existing properties or procedures with the same name.</value> </data> <data name="Specifies_that_a_property_or_procedure_can_be_overridden_by_an_identically_named_property_or_procedure_in_a_derived_class" xml:space="preserve"> <value>Specifies that a property or procedure can be overridden by an identically named property or procedure in a derived class.</value> </data> <data name="Specifies_that_a_property_or_procedure_overrides_an_identically_named_property_or_procedure_inherited_from_a_base_class" xml:space="preserve"> <value>Specifies that a property or procedure overrides an identically named property or procedure inherited from a base class.</value> </data> <data name="Specifies_that_a_procedure_parameter_takes_an_optional_array_of_elements_of_the_specified_type" xml:space="preserve"> <value>Specifies that a procedure parameter takes an optional array of elements of the specified type.</value> </data> <data name="Indicates_that_a_method_class_or_structure_declaration_is_a_partial_definition_of_the_method_class_or_structure" xml:space="preserve"> <value>Indicates that a method, class, or structure declaration is a partial definition of the method, class, or structure.</value> </data> <data name="Returns_the_sum_of_two_numbers_or_the_positive_value_of_a_numeric_expression" xml:space="preserve"> <value>Returns the sum of two numbers, or the positive value of a numeric expression.</value> </data> <data name="Prevents_the_contents_of_an_array_from_being_cleared_when_the_dimensions_of_the_array_are_changed" xml:space="preserve"> <value>Prevents the contents of an array from being cleared when the dimensions of the array are changed.</value> </data> <data name="Specifies_that_one_or_more_declared_programming_elements_are_accessible_only_from_within_their_module_class_or_structure" xml:space="preserve"> <value>Specifies that one or more declared programming elements are accessible only from within their module, class, or structure.</value> </data> <data name="Declares_the_name_of_a_property_and_the_property_procedures_used_to_store_and_retrieve_the_value_of_the_property" xml:space="preserve"> <value>Declares the name of a property, and the property procedures used to store and retrieve the value of the property.</value> </data> <data name="Specifies_that_one_or_more_declared_members_of_a_class_are_accessible_from_anywhere_in_the_same_assembly_their_own_classes_and_derived_classes" xml:space="preserve"> <value>Specifies that one or more declared members of a class are accessible from anywhere in the same assembly, their own classes, and derived classes.</value> </data> <data name="Specifies_that_one_or_more_declared_programming_elements_are_accessible_only_from_within_their_own_class_or_from_a_derived_class" xml:space="preserve"> <value>Specifies that one or more declared programming elements are accessible only from within their own class or from a derived class.</value> </data> <data name="Specifies_that_one_or_more_declared_programming_elements_have_no_access_restrictions" xml:space="preserve"> <value>Specifies that one or more declared programming elements have no access restrictions.</value> </data> <data name="Specifies_that_a_variable_or_property_can_be_read_but_not_written_to" xml:space="preserve"> <value>Specifies that a variable or property can be read but not written to.</value> </data> <data name="Reallocates_storage_space_for_an_array_variable" xml:space="preserve"> <value>Reallocates storage space for an array variable.</value> </data> <data name="Performs_an_arithmetic_right_shift_on_a_bit_pattern" xml:space="preserve"> <value>Performs an arithmetic right shift on a bit pattern</value> </data> <data name="Declares_a_Set_property_procedure_that_is_used_to_assign_a_value_to_a_property" xml:space="preserve"> <value>Declares a Set property procedure that is used to assign a value to a property.</value> </data> <data name="Specifies_that_a_declared_programming_element_redeclares_and_hides_an_identically_named_element_in_a_base_class" xml:space="preserve"> <value>Specifies that a declared programming element redeclares and hides an identically named element in a base class.</value> </data> <data name="Specifies_that_one_or_more_declared_programming_elements_are_associated_with_all_instances_of_a_class_or_structure" xml:space="preserve"> <value>Specifies that one or more declared programming elements are associated with all instances of a class or structure.</value> </data> <data name="Specifies_that_one_or_more_declared_local_variables_are_to_remain_in_existence_and_retain_their_latest_values_after_the_procedure_in_which_they_are_declared_terminates" xml:space="preserve"> <value>Specifies that one or more declared local variables are to remain in existence and retain their latest values after the procedure in which they are declared terminates.</value> </data> <data name="Declares_the_name_of_a_structure_and_introduces_the_definition_of_the_variables_properties_events_and_procedures_that_make_up_the_structure" xml:space="preserve"> <value>Declares the name of a structure and introduces the definition of the variables, properties, events, and procedures that make up the structure.</value> </data> <data name="Declares_the_name_parameters_and_code_that_define_a_Sub_procedure_that_is_a_procedure_that_does_not_return_a_value_to_the_calling_code" xml:space="preserve"> <value>Declares the name, parameters, and code that define a Sub procedure, that is, a procedure that does not return a value to the calling code.</value> </data> <data name="Separates_the_beginning_and_ending_values_of_a_loop_counter_or_array_bounds_or_that_of_a_value_match_range" xml:space="preserve"> <value>Separates the beginning and ending values of a loop counter or array bounds or that of a value match range.</value> </data> <data name="Determines_the_run_time_type_of_an_object_reference_variable_and_compares_it_to_a_data_type_Returns_True_or_False_depending_on_whether_the_two_types_are_compatible_result_TypeOf_objectExpression_Is_typeName" xml:space="preserve"> <value>Determines the run-time type of an object reference variable and compares it to a data type. Returns True or False depending, on whether the two types are compatible. &lt;result&gt; = TypeOf &lt;objectExpression&gt; Is &lt;typeName&gt;</value> </data> <data name="Used_in_a_Declare_statement_Specifies_that_Visual_Basic_should_marshal_all_strings_to_Unicode_values_in_a_call_into_an_external_procedure_and_should_look_up_the_procedure_without_modifying_its_name" xml:space="preserve"> <value>Used in a Declare statement. Specifies that Visual Basic should marshal all strings to Unicode values in a call into an external procedure, and should look up the procedure without modifying its name.</value> </data> <data name="Indicates_that_a_conversion_operator_CType_converts_a_class_or_structure_to_a_type_that_can_hold_all_possible_values_of_the_original_class_or_structure" xml:space="preserve"> <value>Indicates that a conversion operator (CType) converts a class or structure to a type that can hold all possible values of the original class or structure.</value> </data> <data name="Specifies_that_one_or_more_declared_member_variables_refer_to_an_instance_of_a_class_that_can_raise_events" xml:space="preserve"> <value>Specifies that one or more declared member variables refer to an instance of a class that can raise events</value> </data> <data name="Specifies_that_a_property_can_be_written_to_but_not_read" xml:space="preserve"> <value>Specifies that a property can be written to but not read.</value> </data> <data name="Performs_a_logical_exclusion_on_two_Boolean_expressions_or_a_bitwise_exclusion_on_two_numeric_expressions_For_Boolean_expressions_returns_True_if_exactly_one_of_the_expressions_evaluates_to_True_Both_expressions_are_always_evaluated_result_expression1_Xor_expression2" xml:space="preserve"> <value>Performs a logical exclusion on two Boolean expressions, or a bitwise exclusion on two numeric expressions. For Boolean expressions, returns True if exactly one of the expressions evaluates to True. Both expressions are always evaluated. &lt;result&gt; = &lt;expression1&gt; Xor &lt;expression2&gt;</value> </data> <data name="Applies_an_aggregation_function_such_as_Sum_Average_or_Count_to_a_sequence" xml:space="preserve"> <value>Applies an aggregation function, such as Sum, Average, or Count to a sequence.</value> </data> <data name="Specifies_the_sort_order_for_an_Order_By_clause_in_a_query_The_smallest_element_will_appear_first" xml:space="preserve"> <value>Specifies the sort order for an Order By clause in a query. The smallest element will appear first.</value> </data> <data name="Asynchronously_waits_for_the_task_to_finish" xml:space="preserve"> <value>Asynchronously waits for the task to finish.</value> </data> <data name="Sets_the_string_comparison_method_specified_in_Option_Compare_to_a_strict_binary_sort_order" xml:space="preserve"> <value>Sets the string comparison method specified in Option Compare to a strict binary sort order.</value> </data> <data name="Specifies_the_element_keys_used_for_grouping_in_Group_By_or_sort_order_in_Order_By" xml:space="preserve"> <value>Specifies the element keys used for grouping (in Group By) or sort order (in Order By).</value> </data> <data name="Transfers_execution_to_a_Function_Sub_or_dynamic_link_library_DLL_procedure_bracket_Call_bracket_procedureName_bracket_argumentList_bracket" xml:space="preserve"> <value>Transfers execution to a Function, Sub, or dynamic-link library (DLL) procedure. [Call] &lt;procedureName&gt; [(&lt;argumentList&gt;)]</value> </data> <data name="Introduces_the_statements_to_run_if_none_of_the_previous_cases_in_the_Select_Case_statement_returns_True" xml:space="preserve"> <value>Introduces the statements to run if none of the previous cases in the Select Case statement returns True.</value> </data> <data name="Followed_by_a_comparison_operator_and_then_an_expression_Case_Is_introduces_the_statements_to_run_if_the_Select_Case_expression_combined_with_the_Case_Is_expression_evaluates_to_True" xml:space="preserve"> <value>Followed by a comparison operator and then an expression, Case Is introduces the statements to run if the Select Case expression combined with the Case Is expression evaluates to True.</value> </data> <data name="Introduces_a_value_or_set_of_values_against_which_the_value_of_an_expression_in_a_Select_Case_statement_is_to_be_tested_Case_expression_expression1_To_expression2_bracket_Is_bracket_comparisonOperator_expression" xml:space="preserve"> <value>Introduces a value, or set of values, against which the value of an expression in a Select Case statement is to be tested. Case {&lt;expression&gt;|&lt;expression1&gt; To &lt;expression2&gt;|[Is] &lt;comparisonOperator&gt; &lt;expression&gt;}</value> </data> <data name="Introduces_a_statement_block_to_be_run_if_the_specified_exception_occurs_inside_a_Try_block" xml:space="preserve"> <value>Introduces a statement block to be run if the specified exception occurs inside a Try block.</value> </data> <data name="Sets_the_default_comparison_method_to_use_when_comparing_string_data_When_set_to_Text_uses_a_text_sort_order_that_is_not_case_sensitive_When_set_to_Binary_uses_a_strict_binary_sort_order_Option_Compare_Binary_Text" xml:space="preserve"> <value>Sets the default comparison method to use when comparing string data. When set to Text, uses a text sort order that is not case sensitive. When set to Binary, uses a strict binary sort order. Option Compare {Binary | Text}</value> </data> <data name="Defines_a_conditional_compiler_constant_Conditional_compiler_constants_are_always_private_to_the_file_in_which_they_appear_The_expressions_used_to_initialize_them_can_contain_only_conditional_compiler_constants_and_literals" xml:space="preserve"> <value>Defines a conditional compiler constant. Conditional compiler constants are always private to the file in which they appear. The expressions used to initialize them can contain only conditional compiler constants and literals.</value> </data> <data name="Transfers_execution_immediately_to_the_next_iteration_of_the_Do_loop" xml:space="preserve"> <value>Transfers execution immediately to the next iteration of the Do loop.</value> </data> <data name="Transfers_execution_immediately_to_the_next_iteration_of_the_For_loop" xml:space="preserve"> <value>Transfers execution immediately to the next iteration of the For loop.</value> </data> <data name="Transfers_execution_immediately_to_the_next_iteration_of_the_loop_Can_be_used_in_a_Do_loop_a_For_loop_or_a_While_loop" xml:space="preserve"> <value>Transfers execution immediately to the next iteration of the loop. Can be used in a Do loop, a For loop, or a While loop.</value> </data> <data name="Transfers_execution_immediately_to_the_next_iteration_of_the_While_loop" xml:space="preserve"> <value>Transfers execution immediately to the next iteration of the While loop.</value> </data> <data name="Specifies_the_sort_order_for_an_Order_By_clause_in_a_query_The_largest_element_will_appear_first" xml:space="preserve"> <value>Specifies the sort order for an Order By clause in a query. The largest element will appear first.</value> </data> <data name="Restricts_the_values_of_a_query_result_to_eliminate_duplicate_values" xml:space="preserve"> <value>Restricts the values of a query result to eliminate duplicate values.</value> </data> <data name="Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_or_until_the_condition_becomes_true_Do_Loop_While_Until_condition" xml:space="preserve"> <value>Repeats a block of statements while a Boolean condition is true, or until the condition becomes true. Do...Loop {While | Until} &lt;condition&gt;</value> </data> <data name="Repeats_a_block_of_statements_until_a_Boolean_condition_becomes_true_Do_Until_condition_Loop" xml:space="preserve"> <value>Repeats a block of statements until a Boolean condition becomes true. Do Until &lt;condition&gt;...Loop</value> </data> <data name="Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_Do_While_condition_Loop" xml:space="preserve"> <value>Repeats a block of statements while a Boolean condition is true. Do While &lt;condition&gt;...Loop</value> </data> <data name="Introduces_a_group_of_statements_in_an_SharpIf_statement_that_is_compiled_if_no_previous_condition_evaluates_to_True" xml:space="preserve"> <value>Introduces a group of statements in an #If statement that is compiled if no previous condition evaluates to True.</value> </data> <data name="Introduces_a_condition_in_an_SharpIf_statement_that_is_tested_if_the_previous_conditional_test_evaluates_to_False" xml:space="preserve"> <value>Introduces a condition in an #If statement that is tested if the previous conditional test evaluates to False.</value> </data> <data name="Introduces_a_condition_in_an_If_statement_that_is_to_be_tested_if_the_previous_conditional_test_fails" xml:space="preserve"> <value>Introduces a condition in an If statement that is to be tested if the previous conditional test fails.</value> </data> <data name="Introduces_a_group_of_statements_in_an_If_statement_that_is_executed_if_no_previous_condition_evaluates_to_True" xml:space="preserve"> <value>Introduces a group of statements in an If statement that is executed if no previous condition evaluates to True.</value> </data> <data name="Terminates_the_definition_of_an_SharpIf_block" xml:space="preserve"> <value>Terminates the definition of an #If block.</value> </data> <data name="Stops_execution_immediately" xml:space="preserve"> <value>Stops execution immediately.</value> </data> <data name="Terminates_a_SharpRegion_block" xml:space="preserve"> <value>Terminates a #Region block.</value> </data> <data name="Specifies_the_relationship_between_element_keys_to_use_as_the_basis_of_a_join_operation" xml:space="preserve"> <value>Specifies the relationship between element keys to use as the basis of a join operation.</value> </data> <data name="Simulates_the_occurrence_of_an_error" xml:space="preserve"> <value>Simulates the occurrence of an error.</value> </data> <data name="Exits_a_Do_loop_and_transfers_execution_immediately_to_the_statement_following_the_Loop_statement" xml:space="preserve"> <value>Exits a Do loop and transfers execution immediately to the statement following the Loop statement.</value> </data> <data name="Exits_a_For_loop_and_transfers_execution_immediately_to_the_statement_following_the_Next_statement" xml:space="preserve"> <value>Exits a For loop and transfers execution immediately to the statement following the Next statement.</value> </data> <data name="Exits_a_procedure_or_block_and_transfers_execution_immediately_to_the_statement_following_the_procedure_call_or_block_definition_Exit_Do_For_Function_Property_Select_Sub_Try_While" xml:space="preserve"> <value>Exits a procedure or block and transfers execution immediately to the statement following the procedure call or block definition. Exit {Do | For | Function | Property | Select | Sub | Try | While}</value> </data> <data name="Exits_a_Select_block_and_transfers_execution_immediately_to_the_statement_following_the_End_Select_statement" xml:space="preserve"> <value>Exits a Select block and transfers execution immediately to the statement following the End Select statement.</value> </data> <data name="Exits_a_Try_block_and_transfers_execution_immediately_to_the_statement_following_the_End_Try_statement" xml:space="preserve"> <value>Exits a Try block and transfers execution immediately to the statement following the End Try statement.</value> </data> <data name="Exits_a_While_loop_and_transfers_execution_immediately_to_the_statement_following_the_End_While_statement" xml:space="preserve"> <value>Exits a While loop and transfers execution immediately to the statement following the End While statement.</value> </data> <data name="When_set_to_On_requires_explicit_declaration_of_all_variables_using_a_Dim_Private_Public_or_ReDim_statement_Option_Explicit_On_Off" xml:space="preserve"> <value>When set to On, requires explicit declaration of all variables, using a Dim, Private, Public, or ReDim statement. Option Explicit {On | Off}</value> </data> <data name="Represents_a_Boolean_value_that_fails_a_conditional_test" xml:space="preserve"> <value>Represents a Boolean value that fails a conditional test.</value> </data> <data name="Introduces_a_statement_block_to_be_run_before_exiting_a_Try_structure" xml:space="preserve"> <value>Introduces a statement block to be run before exiting a Try structure.</value> </data> <data name="Introduces_a_loop_that_is_repeated_for_each_element_in_a_collection" xml:space="preserve"> <value>Introduces a loop that is repeated for each element in a collection.</value> </data> <data name="Introduces_a_loop_that_is_iterated_a_specified_number_of_times" xml:space="preserve"> <value>Introduces a loop that is iterated a specified number of times.</value> </data> <data name="Identifies_a_list_of_values_as_a_collection_initializer" xml:space="preserve"> <value>Identifies a list of values as a collection initializer</value> </data> <data name="Branches_unconditionally_to_a_specified_line_in_a_procedure" xml:space="preserve"> <value>Branches unconditionally to a specified line in a procedure.</value> </data> <data name="Groups_elements_that_have_a_common_key" xml:space="preserve"> <value>Groups elements that have a common key.</value> </data> <data name="Combines_the_elements_of_two_sequences_and_groups_the_results_The_join_operation_is_based_on_matching_keys" xml:space="preserve"> <value>Combines the elements of two sequences and groups the results. The join operation is based on matching keys.</value> </data> <data name="Use_Group_to_specify_that_a_group_named_0_should_be_created" xml:space="preserve"> <value>Use 'Group' to specify that a group named '{0}' should be created.</value> </data> <data name="Use_Group_to_specify_that_a_group_named_Group_should_be_created" xml:space="preserve"> <value>Use 'Group' to specify that a group named 'Group' should be created.</value> </data> <data name="Conditionally_compiles_selected_blocks_of_code_depending_on_the_value_of_an_expression" xml:space="preserve"> <value>Conditionally compiles selected blocks of code, depending on the value of an expression.</value> </data> <data name="Conditionally_executes_a_group_of_statements_depending_on_the_value_of_an_expression" xml:space="preserve"> <value>Conditionally executes a group of statements, depending on the value of an expression.</value> </data> <data name="When_set_to_On_allows_the_use_of_local_type_inference_in_declaring_variables_Option_Infer_On_Off" xml:space="preserve"> <value>When set to On, allows the use of local type inference in declaring variables. Option Infer {On | Off}</value> </data> <data name="Specifies_an_identifier_that_can_serve_as_a_reference_to_the_results_of_a_join_or_grouping_subexpression" xml:space="preserve"> <value>Specifies an identifier that can serve as a reference to the results of a join or grouping subexpression.</value> </data> <data name="Combines_the_elements_of_two_sequences_The_join_operation_is_based_on_matching_keys" xml:space="preserve"> <value>Combines the elements of two sequences. The join operation is based on matching keys.</value> </data> <data name="Identifies_a_key_field_in_an_anonymous_type_definition" xml:space="preserve"> <value>Identifies a key field in an anonymous type definition.</value> </data> <data name="Computes_a_value_for_each_item_in_the_query_and_assigns_the_value_to_a_new_range_variable" xml:space="preserve"> <value>Computes a value for each item in the query, and assigns the value to a new range variable.</value> </data> <data name="Terminates_a_loop_that_is_introduced_with_a_Do_statement" xml:space="preserve"> <value>Terminates a loop that is introduced with a Do statement.</value> </data> <data name="Repeats_a_block_of_statements_until_a_Boolean_condition_becomes_true_Do_Loop_Until_condition" xml:space="preserve"> <value>Repeats a block of statements until a Boolean condition becomes true. Do...Loop Until &lt;condition&gt;</value> </data> <data name="Repeats_a_block_of_statements_while_a_Boolean_condition_is_true_Do_Loop_While_condition" xml:space="preserve"> <value>Repeats a block of statements while a Boolean condition is true. Do...Loop While &lt;condition&gt;</value> </data> <data name="Provides_a_way_to_refer_to_the_current_instance_of_a_class_or_structure_that_is_the_instance_in_which_the_code_is_running" xml:space="preserve"> <value>Provides a way to refer to the current instance of a class or structure, that is, the instance in which the code is running.</value> </data> <data name="Provides_a_way_to_refer_to_the_base_class_of_the_current_class_instance_You_cannot_use_MyBase_to_call_MustOverride_base_methods" xml:space="preserve"> <value>Provides a way to refer to the base class of the current class instance. You cannot use MyBase to call MustOverride base methods.</value> </data> <data name="Provides_a_way_to_refer_to_the_class_instance_members_as_originally_implemented_ignoring_any_derived_class_overrides" xml:space="preserve"> <value>Provides a way to refer to the class instance members as originally implemented, ignoring any derived class overrides.</value> </data> <data name="Creates_a_new_object_instance" xml:space="preserve"> <value>Creates a new object instance.</value> </data> <data name="Terminates_a_loop_that_iterates_through_the_values_of_a_loop_variable" xml:space="preserve"> <value>Terminates a loop that iterates through the values of a loop variable.</value> </data> <data name="Represents_the_default_value_of_any_data_type" xml:space="preserve"> <value>Represents the default value of any data type.</value> </data> <data name="Turns_a_compiler_option_off" xml:space="preserve"> <value>Turns a compiler option off.</value> </data> <data name="Enables_the_error_handling_routine_that_starts_at_the_line_specified_in_the_line_argument_The_specified_line_must_be_in_the_same_procedure_as_the_On_Error_statement_On_Error_GoTo_bracket_label_0_1_bracket" xml:space="preserve"> <value>Enables the error-handling routine that starts at the line specified in the line argument. The specified line must be in the same procedure as the On Error statement. On Error GoTo [&lt;label&gt; | 0 | -1]</value> </data> <data name="When_a_run_time_error_occurs_execution_transfers_to_the_statement_following_the_statement_or_procedure_call_that_resulted_in_the_error" xml:space="preserve"> <value>When a run-time error occurs, execution transfers to the statement following the statement or procedure call that resulted in the error.</value> </data> <data name="Turns_a_compiler_option_on" xml:space="preserve"> <value>Turns a compiler option on.</value> </data> <data name="Specifies_the_element_keys_used_to_correlate_sequences_for_a_join_operation" xml:space="preserve"> <value>Specifies the element keys used to correlate sequences for a join operation.</value> </data> <data name="Specifies_the_sort_order_for_columns_in_a_query_Can_be_followed_by_either_the_Ascending_or_the_Descending_keyword_If_neither_is_specified_Ascending_is_used" xml:space="preserve"> <value>Specifies the sort order for columns in a query. Can be followed by either the Ascending or the Descending keyword. If neither is specified, Ascending is used.</value> </data> <data name="Specifies_the_statements_to_run_when_the_event_is_raised_by_the_RaiseEvent_statement_RaiseEvent_delegateSignature_End_RaiseEvent" xml:space="preserve"> <value>Specifies the statements to run when the event is raised by the RaiseEvent statement. RaiseEvent(&lt;delegateSignature&gt;)...End RaiseEvent</value> </data> <data name="Triggers_an_event_declared_at_module_level_within_a_class_form_or_document_RaiseEvent_eventName_bracket_argumentList_bracket" xml:space="preserve"> <value>Triggers an event declared at module level within a class, form, or document. RaiseEvent &lt;eventName&gt; [(&lt;argumentList&gt;)]</value> </data> <data name="Collapses_and_hides_sections_of_code_in_Visual_Basic_files" xml:space="preserve"> <value>Collapses and hides sections of code in Visual Basic files.</value> </data> <data name="Returns_execution_to_the_code_that_called_the_Function_Sub_Get_Set_or_Operator_procedure_Return_or_Return_expression" xml:space="preserve"> <value>Returns execution to the code that called the Function, Sub, Get, Set, or Operator procedure. Return -or- Return &lt;expression&gt;</value> </data> <data name="Runs_one_of_several_groups_of_statements_depending_on_the_value_of_an_expression" xml:space="preserve"> <value>Runs one of several groups of statements, depending on the value of an expression.</value> </data> <data name="Specifies_which_columns_to_include_in_the_result_of_a_query" xml:space="preserve"> <value>Specifies which columns to include in the result of a query.</value> </data> <data name="Skips_elements_up_to_a_specified_position_in_the_collection" xml:space="preserve"> <value>Skips elements up to a specified position in the collection.</value> </data> <data name="Specifies_how_much_to_increment_between_each_loop_iteration" xml:space="preserve"> <value>Specifies how much to increment between each loop iteration.</value> </data> <data name="Suspends_program_execution" xml:space="preserve"> <value>Suspends program execution.</value> </data> <data name="When_set_to_On_restricts_implicit_data_type_conversions_to_only_widening_conversions_Option_Strict_On_Off" xml:space="preserve"> <value>When set to On, restricts implicit data type conversions to only widening conversions. Option Strict {On | Off}</value> </data> <data name="Ensures_that_multiple_threads_do_not_execute_the_statement_block_at_the_same_time_SyncLock_object_End_Synclock" xml:space="preserve"> <value>Ensures that multiple threads do not execute the statement block at the same time. SyncLock &lt;object&gt;...End Synclock</value> </data> <data name="Includes_elements_up_to_a_specified_position_in_the_collection" xml:space="preserve"> <value>Includes elements up to a specified position in the collection.</value> </data> <data name="Sets_the_string_comparison_method_specified_in_Option_Compare_to_a_text_sort_order_that_is_not_case_sensitive" xml:space="preserve"> <value>Sets the string comparison method specified in Option Compare to a text sort order that is not case sensitive.</value> </data> <data name="Introduces_a_statement_block_to_be_compiled_or_executed_if_a_tested_condition_is_true" xml:space="preserve"> <value>Introduces a statement block to be compiled or executed if a tested condition is true.</value> </data> <data name="Throws_an_exception_within_a_procedure_so_that_you_can_handle_it_with_structured_or_unstructured_exception_handling_code" xml:space="preserve"> <value>Throws an exception within a procedure so that you can handle it with structured or unstructured exception-handling code.</value> </data> <data name="Represents_a_Boolean_value_that_passes_a_conditional_test" xml:space="preserve"> <value>Represents a Boolean value that passes a conditional test.</value> </data> <data name="Provides_a_way_to_handle_some_or_all_possible_errors_that_might_occur_in_a_given_block_of_code_while_still_running_the_code_Try_bracket_Catch_bracket_Catch_Finally_End_Try" xml:space="preserve"> <value>Provides a way to handle some or all possible errors that might occur in a given block of code, while still running the code. Try...[Catch]...{Catch | Finally}...End Try</value> </data> <data name="A_Using_block_does_three_things_colon_it_creates_and_initializes_variables_in_the_resource_list_it_runs_the_code_in_the_block_and_it_disposes_of_the_variables_before_exiting_Resources_used_in_the_Using_block_must_implement_System_IDisposable_Using_resource1_bracket_resource2_bracket_End_Using" xml:space="preserve"> <value>A Using block does three things: it creates and initializes variables in the resource list, it runs the code in the block, and it disposes of the variables before exiting. Resources used in the Using block must implement System.IDisposable. Using &lt;resource1&gt;[, &lt;resource2&gt;]...End Using</value> </data> <data name="Adds_a_conditional_test_to_a_Catch_statement_Exceptions_are_caught_by_that_Catch_statement_only_when_the_conditional_test_that_follows_the_When_keyword_evaluates_to_True" xml:space="preserve"> <value>Adds a conditional test to a Catch statement. Exceptions are caught by that Catch statement only when the conditional test that follows the When keyword evaluates to True.</value> </data> <data name="Specifies_the_filtering_condition_for_a_range_variable_in_a_query" xml:space="preserve"> <value>Specifies the filtering condition for a range variable in a query.</value> </data> <data name="Runs_a_series_of_statements_as_long_as_a_given_condition_is_true" xml:space="preserve"> <value>Runs a series of statements as long as a given condition is true.</value> </data> <data name="Specifies_a_condition_for_Skip_and_Take_operations_Elements_will_be_bypassed_or_included_as_long_as_the_condition_is_true" xml:space="preserve"> <value>Specifies a condition for Skip and Take operations. Elements will be bypassed or included as long as the condition is true.</value> </data> <data name="Specifies_the_declaration_of_property_initializations_in_an_object_initializer_New_typeName_With_bracket_property_expression_bracket_bracket_bracket" xml:space="preserve"> <value>Specifies the declaration of property initializations in an object initializer. New &lt;typeName&gt; With {[.&lt;property&gt; = &lt;expression&gt;][,...]}</value> </data> <data name="Runs_a_series_of_statements_that_refer_to_a_single_object_or_structure_With_object_End_With" xml:space="preserve"> <value>Runs a series of statements that refer to a single object or structure. With &lt;object&gt;...End With</value> </data> <data name="Produces_an_element_of_an_IEnumerable_or_IEnumerator" xml:space="preserve"> <value>Produces an element of an IEnumerable or IEnumerator.</value> </data> <data name="Defines_an_asynchronous_lambda_expression_that_can_use_the_Await_operator_Can_be_used_wherever_a_delegate_type_is_expected_Async_Sub_Function_parameterList_expression" xml:space="preserve"> <value>Defines an asynchronous lambda expression that can use the Await operator. Can be used wherever a delegate type is expected. Async Sub/Function(&lt;parameterList&gt;) &lt;expression&gt;</value> </data> <data name="Defines_a_lambda_expression_that_calculates_and_returns_a_single_value_Can_be_used_wherever_a_delegate_type_is_expected_Function_parameterList_expression" xml:space="preserve"> <value>Defines a lambda expression that calculates and returns a single value. Can be used wherever a delegate type is expected. Function(&lt;parameterList&gt;) &lt;expression&gt;</value> </data> <data name="Defines_a_lambda_expression_that_can_execute_statements_and_does_not_return_a_value_Can_be_used_wherever_a_delegate_type_is_expected_Sub_parameterList_statement" xml:space="preserve"> <value>Defines a lambda expression that can execute statements and does not return a value. Can be used wherever a delegate type is expected. Sub(&lt;parameterList&gt;) &lt;statement&gt;</value> </data> <data name="Disables_reporting_of_specified_warnings_in_the_portion_of_the_source_file_below_the_current_line" xml:space="preserve"> <value>Disables reporting of specified warnings in the portion of the source file below the current line.</value> </data> <data name="Enables_reporting_of_specified_warnings_in_the_portion_of_the_source_file_below_the_current_line" xml:space="preserve"> <value>Enables reporting of specified warnings in the portion of the source file below the current line.</value> </data> <data name="Insert_Await" xml:space="preserve"> <value>Insert 'Await'.</value> </data> <data name="Make_0_an_Async_Function" xml:space="preserve"> <value>Make {0} an Async Function.</value> </data> <data name="Convert_0_to_Iterator" xml:space="preserve"> <value>Convert {0} to Iterator</value> </data> <data name="Replace_Return_with_Yield" xml:space="preserve"> <value>Replace 'Return' with 'Yield</value> </data> <data name="Use_the_correct_control_variable" xml:space="preserve"> <value>Use the correct control variable</value> </data> <data name="NameOf_function" xml:space="preserve"> <value>NameOf function</value> </data> <data name="Generate_narrowing_conversion_in_0" xml:space="preserve"> <value>Generate narrowing conversion in '{0}'</value> </data> <data name="Generate_widening_conversion_in_0" xml:space="preserve"> <value>Generate widening conversion in '{0}'</value> </data> <data name="Try_block" xml:space="preserve"> <value>Try block</value> <comment>{Locked="Try"} "Try" is a VB keyword and should not be localized.</comment> </data> <data name="Catch_clause" xml:space="preserve"> <value>Catch clause</value> <comment>{Locked="Catch"} "Catch" is a VB keyword and should not be localized.</comment> </data> <data name="Finally_clause" xml:space="preserve"> <value>Finally clause</value> <comment>{Locked="Finally"} "Finally" is a VB keyword and should not be localized.</comment> </data> <data name="Using_statement" xml:space="preserve"> <value>Using statement</value> <comment>{Locked="Using"} "Using" is a VB keyword and should not be localized.</comment> </data> <data name="Using_block" xml:space="preserve"> <value>Using block</value> <comment>{Locked="Using"} "Using" is a VB keyword and should not be localized.</comment> </data> <data name="With_statement" xml:space="preserve"> <value>With statement</value> <comment>{Locked="With"} "With" is a VB keyword and should not be localized.</comment> </data> <data name="With_block" xml:space="preserve"> <value>With block</value> <comment>{Locked="With"} "With" is a VB keyword and should not be localized.</comment> </data> <data name="SyncLock_statement" xml:space="preserve"> <value>SyncLock statement</value> <comment>{Locked="SyncLock"} "SyncLock" is a VB keyword and should not be localized.</comment> </data> <data name="SyncLock_block" xml:space="preserve"> <value>SyncLock block</value> <comment>{Locked="SyncLock"} "SyncLock" is a VB keyword and should not be localized.</comment> </data> <data name="For_Each_statement" xml:space="preserve"> <value>For Each statement</value> <comment>{Locked="For Each"} "For Each" is a VB keyword and should not be localized.</comment> </data> <data name="For_Each_block" xml:space="preserve"> <value>For Each block</value> <comment>{Locked="For Each"} "For Each" is a VB keyword and should not be localized.</comment> </data> <data name="On_Error_statement" xml:space="preserve"> <value>On Error statement</value> <comment>{Locked="On Error"} "On Error" is a VB keyword and should not be localized.</comment> </data> <data name="Resume_statement" xml:space="preserve"> <value>Resume statement</value> <comment>{Locked="Resume"} "Resume" is a VB keyword and should not be localized.</comment> </data> <data name="Yield_statement" xml:space="preserve"> <value>Yield statement</value> <comment>{Locked="Yield"} "Yield" is a VB keyword and should not be localized.</comment> </data> <data name="Await_expression" xml:space="preserve"> <value>Await expression</value> <comment>{Locked="Await"} "Await" is a VB keyword and should not be localized.</comment> </data> <data name="Lambda" xml:space="preserve"> <value>Lambda</value> </data> <data name="Where_clause" xml:space="preserve"> <value>Where clause</value> <comment>{Locked="Where"} "Where" is a VB keyword and should not be localized.</comment> </data> <data name="Select_clause" xml:space="preserve"> <value>Select clause</value> <comment>{Locked="Select"} "Select" is a VB keyword and should not be localized.</comment> </data> <data name="From_clause" xml:space="preserve"> <value>From clause</value> <comment>{Locked="From"} "From" is a VB keyword and should not be localized.</comment> </data> <data name="Aggregate_clause" xml:space="preserve"> <value>Aggregate clause</value> <comment>{Locked="Aggregate"} "Aggregate" is a VB keyword and should not be localized.</comment> </data> <data name="Let_clause" xml:space="preserve"> <value>Let clause</value> <comment>{Locked="Let"} "Let" is a VB keyword and should not be localized.</comment> </data> <data name="Join_clause" xml:space="preserve"> <value>Join clause</value> <comment>{Locked="Join"} "Join" is a VB keyword and should not be localized.</comment> </data> <data name="Group_Join_clause" xml:space="preserve"> <value>Group Join clause</value> <comment>{Locked="Group Join"} "Group Join" is a VB keyword and should not be localized.</comment> </data> <data name="Group_By_clause" xml:space="preserve"> <value>Group By clause</value> <comment>{Locked="Group By"} "Group By" is a VB keyword and should not be localized.</comment> </data> <data name="Function_aggregation" xml:space="preserve"> <value>Function aggregation</value> </data> <data name="Take_While_clause" xml:space="preserve"> <value>Take While clause</value> <comment>{Locked="Take While"} "Take While" is a VB keyword and should not be localized.</comment> </data> <data name="Skip_While_clause" xml:space="preserve"> <value>Skip While clause</value> <comment>{Locked="Skip While"} "Skip While" is a VB keyword and should not be localized.</comment> </data> <data name="Ordering_clause" xml:space="preserve"> <value>Ordering clause</value> <comment>{Locked="Ordering"} "Ordering" is a VB keyword and should not be localized.</comment> </data> <data name="Join_condition" xml:space="preserve"> <value>Join condition</value> <comment>{Locked="Join"} "Join" is a VB keyword and should not be localized.</comment> </data> <data name="option_" xml:space="preserve"> <value>option</value> <comment>{Locked}</comment> </data> <data name="import" xml:space="preserve"> <value>import</value> <comment>{Locked}</comment> </data> <data name="structure_" xml:space="preserve"> <value>structure</value> <comment>{Locked}</comment> </data> <data name="module_" xml:space="preserve"> <value>module</value> <comment>{Locked}</comment> </data> <data name="WithEvents_field" xml:space="preserve"> <value>WithEvents field</value> <comment>{Locked="WithEvents"} "WithEvents" is a VB keyword and should not be localized.</comment> </data> <data name="as_clause" xml:space="preserve"> <value>as clause</value> <comment>{Locked="as"} "as" is a VB keyword and should not be localized.</comment> </data> <data name="type_parameters" xml:space="preserve"> <value>type parameters</value> </data> <data name="parameters" xml:space="preserve"> <value>parameters</value> </data> <data name="attributes" xml:space="preserve"> <value>attributes</value> </data> <data name="Too_many_arguments_to_0" xml:space="preserve"> <value>Too many arguments to '{0}'.</value> </data> <data name="Type_0_is_not_defined" xml:space="preserve"> <value>Type '{0}' is not defined.</value> </data> <data name="Add_Overloads" xml:space="preserve"> <value>Add 'Overloads'</value> <comment>{Locked="Overloads"} "Overloads" is a VB keyword and should not be localized.</comment> </data> <data name="Add_a_metadata_reference_to_specified_assembly_and_all_its_dependencies_e_g_Sharpr_myLib_dll" xml:space="preserve"> <value>Add a metadata reference to specified assembly and all its dependencies, e.g. #r "myLib.dll".</value> </data> <data name="Properties" xml:space="preserve"> <value>Properties</value> </data> <data name="namespace_name" xml:space="preserve"> <value>&lt;namespace name&gt;</value> </data> <data name="Type_a_name_here_to_declare_a_namespace" xml:space="preserve"> <value>Type a name here to declare a namespace.</value> </data> <data name="Type_a_name_here_to_declare_a_partial_class" xml:space="preserve"> <value>Type a name here to declare a partial class.</value> </data> <data name="class_name" xml:space="preserve"> <value>&lt;class name&gt;</value> </data> <data name="interface_name" xml:space="preserve"> <value>&lt;interface name&gt;</value> </data> <data name="module_name" xml:space="preserve"> <value>&lt;module name&gt;</value> </data> <data name="structure_name" xml:space="preserve"> <value>&lt;structure name&gt;</value> </data> <data name="Type_a_name_here_to_declare_a_partial_interface" xml:space="preserve"> <value>Type a name here to declare a partial interface.</value> </data> <data name="Type_a_name_here_to_declare_a_partial_module" xml:space="preserve"> <value>Type a name here to declare a partial module.</value> </data> <data name="Type_a_name_here_to_declare_a_partial_structure" xml:space="preserve"> <value>Type a name here to declare a partial structure.</value> </data> <data name="Event_add_handler_name" xml:space="preserve"> <value>{0}.add</value> <comment>The name of an event add handler where "{0}" is the event name.</comment> </data> <data name="Event_remove_handler_name" xml:space="preserve"> <value>{0}.remove</value> <comment>The name of an event remove handler where "{0}" is the event name.</comment> </data> <data name="Property_getter_name" xml:space="preserve"> <value>{0}.get</value> <comment>The name of a property getter like "public int MyProperty { get; }" where "{0}" is the property name</comment> </data> <data name="Property_setter_name" xml:space="preserve"> <value>{0}.set</value> <comment>The name of a property setter like "public int MyProperty { set; }" where "{0}" is the property name</comment> </data> <data name="Make_Async_Function" xml:space="preserve"> <value>Make Async Function</value> </data> <data name="Make_Async_Sub" xml:space="preserve"> <value>Make Async Sub</value> </data> <data name="Multiple_Types" xml:space="preserve"> <value>&lt;Multiple Types&gt;</value> </data> <data name="Convert_to_Select_Case" xml:space="preserve"> <value>Convert to 'Select Case'</value> </data> <data name="Convert_to_For_Each" xml:space="preserve"> <value>Convert to 'For Each'</value> </data> <data name="Convert_to_For" xml:space="preserve"> <value>Convert to 'For'</value> </data> <data name="Add_Obsolete" xml:space="preserve"> <value>Add &lt;Obsolete&gt;</value> </data> <data name="Add_missing_Imports" xml:space="preserve"> <value>Add missing Imports</value> <comment>{Locked="Import"}</comment> </data> <data name="Add_Shadows" xml:space="preserve"> <value>Add 'Shadows'</value> <comment>{Locked="Shadows"} "Shadows" is a VB keyword and should not be localized.</comment> </data> <data name="Introduce_Using_statement" xml:space="preserve"> <value>Introduce 'Using' statement</value> <comment>{Locked="Using"} "Using" is a VB keyword and should not be localized.</comment> </data> <data name="Make_0_inheritable" xml:space="preserve"> <value>Make '{0}' inheritable</value> </data> <data name="Apply_Me_qualification_preferences" xml:space="preserve"> <value>Apply Me qualification preferences</value> <comment>{Locked="Me"} "Me" is a VB keyword and should not be localized.</comment> </data> <data name="Apply_Imports_directive_placement_preferences" xml:space="preserve"> <value>Apply Imports directive placement preferences</value> <comment>{Locked="Import"} "Import" is a VB keyword and should not be localized.</comment> </data> <data name="Make_private_field_ReadOnly_when_possible" xml:space="preserve"> <value>Make private field ReadOnly when possible</value> <comment>{Locked="ReadOnly"} "ReadOnly" is a VB keyword and should not be localized.</comment> </data> <data name="Organize_Imports" xml:space="preserve"> <value>Organize Imports</value> <comment>{Locked="Import"}</comment> </data> <data name="Change_to_DirectCast" xml:space="preserve"> <value>Change to 'DirectCast'</value> </data> <data name="Change_to_TryCast" xml:space="preserve"> <value>Change to 'TryCast'</value> </data> <data name="Remove_shared_keyword_from_module_member" xml:space="preserve"> <value>Remove 'Shared' keyword from Module member</value> <comment>{Locked="Shared"} "Shared" is a VB keyword and should not be localized.</comment> </data> <data name="_0_Events" xml:space="preserve"> <value>({0} Events)</value> </data> <data name="Shared_constructor" xml:space="preserve"> <value>Shared constructor</value> </data> </root>
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicMethodExtractor.VisualBasicCodeGenerator.CallSiteContainerRewriter.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.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ExtractMethod Partial Friend Class VisualBasicMethodExtractor Partial Private MustInherit Class VisualBasicCodeGenerator Private Class CallSiteContainerRewriter Inherits VisualBasicSyntaxRewriter Private ReadOnly _outmostCallSiteContainer As SyntaxNode Private ReadOnly _statementsOrFieldToInsert As IEnumerable(Of StatementSyntax) Private ReadOnly _variableToRemoveMap As HashSet(Of SyntaxAnnotation) Private ReadOnly _firstStatementOrFieldToReplace As StatementSyntax Private ReadOnly _lastStatementOrFieldToReplace As StatementSyntax Private Shared ReadOnly s_removeAnnotation As SyntaxAnnotation = New SyntaxAnnotation() Public Sub New(outmostCallSiteContainer As SyntaxNode, variableToRemoveMap As HashSet(Of SyntaxAnnotation), firstStatementOrFieldToReplace As StatementSyntax, lastStatementOrFieldToReplace As StatementSyntax, statementsOrFieldToInsert As IEnumerable(Of StatementSyntax)) Contract.ThrowIfNull(outmostCallSiteContainer) Contract.ThrowIfNull(variableToRemoveMap) Contract.ThrowIfNull(firstStatementOrFieldToReplace) Contract.ThrowIfNull(lastStatementOrFieldToReplace) Contract.ThrowIfTrue(statementsOrFieldToInsert.IsEmpty()) Me._outmostCallSiteContainer = outmostCallSiteContainer Me._variableToRemoveMap = variableToRemoveMap Me._statementsOrFieldToInsert = statementsOrFieldToInsert Me._firstStatementOrFieldToReplace = firstStatementOrFieldToReplace Me._lastStatementOrFieldToReplace = lastStatementOrFieldToReplace Contract.ThrowIfFalse(Me._firstStatementOrFieldToReplace.Parent Is Me._lastStatementOrFieldToReplace.Parent) End Sub Public Function Generate() As SyntaxNode Dim result = Visit(Me._outmostCallSiteContainer) ' remove any nodes annotated for removal If result.ContainsAnnotations Then Dim nodesToRemove = result.DescendantNodes(Function(n) n.ContainsAnnotations).Where(Function(n) n.HasAnnotation(s_removeAnnotation)) result = result.RemoveNodes(nodesToRemove, SyntaxRemoveOptions.KeepNoTrivia) End If Return result End Function Private ReadOnly Property ContainerOfStatementsOrFieldToReplace() As SyntaxNode Get Return Me._firstStatementOrFieldToReplace.Parent End Get End Property Public Overrides Function VisitLocalDeclarationStatement(node As LocalDeclarationStatementSyntax) As SyntaxNode node = CType(MyBase.VisitLocalDeclarationStatement(node), LocalDeclarationStatementSyntax) Dim expressionStatements = New List(Of StatementSyntax)() Dim variableDeclarators = New List(Of VariableDeclaratorSyntax)() Dim triviaList = New List(Of SyntaxTrivia)() If Not Me._variableToRemoveMap.ProcessLocalDeclarationStatement(node, expressionStatements, variableDeclarators, triviaList) Then Contract.ThrowIfFalse(expressionStatements.Count = 0) Return node End If Contract.ThrowIfFalse(expressionStatements.Count = 0) If variableDeclarators.Count = 0 AndAlso triviaList.Any(Function(t) t.Kind <> SyntaxKind.WhitespaceTrivia AndAlso t.Kind <> SyntaxKind.EndOfLineTrivia) Then ' well, there are trivia associated with the node. ' we can't just delete the node since then, we will lose ' the trivia. unfortunately, it is not easy to attach the trivia ' to next token. for now, create an empty statement and associate the ' trivia to the statement ' TODO : think about a way to trivia attached to next token Return SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxKind.EmptyToken).WithLeadingTrivia(SyntaxFactory.TriviaList(triviaList))) End If ' return survived var decls If variableDeclarators.Count > 0 Then Return SyntaxFactory.LocalDeclarationStatement( node.Modifiers, SyntaxFactory.SeparatedList(variableDeclarators)).WithPrependedLeadingTrivia(triviaList) End If Return node.WithAdditionalAnnotations(s_removeAnnotation) End Function Public Overrides Function VisitMethodBlock(node As MethodBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then ' make sure we visit nodes under the block Return MyBase.VisitMethodBlock(node) End If Return node.WithSubOrFunctionStatement(ReplaceStatementIfNeeded(node.SubOrFunctionStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))) End Function Public Overrides Function VisitConstructorBlock(node As ConstructorBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then ' make sure we visit nodes under the block Return MyBase.VisitConstructorBlock(node) End If Return node.WithSubNewStatement(ReplaceStatementIfNeeded(node.SubNewStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))) End Function Public Overrides Function VisitOperatorBlock(node As OperatorBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then ' make sure we visit nodes under the block Return MyBase.VisitOperatorBlock(node) End If Return node.WithOperatorStatement(ReplaceStatementIfNeeded(node.OperatorStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))) End Function Public Overrides Function VisitAccessorBlock(node As AccessorBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then ' make sure we visit nodes under the block Return MyBase.VisitAccessorBlock(node) End If Return node.WithAccessorStatement(ReplaceStatementIfNeeded(node.AccessorStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))) End Function Public Overrides Function VisitWhileBlock(node As WhileBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then ' make sure we visit nodes under the switch section Return MyBase.VisitWhileBlock(node) End If Return node.WithWhileStatement(ReplaceStatementIfNeeded(node.WhileStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))) End Function Public Overrides Function VisitUsingBlock(node As UsingBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitUsingBlock(node) End If Return node.WithUsingStatement(ReplaceStatementIfNeeded(node.UsingStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))) End Function Public Overrides Function VisitSyncLockBlock(node As SyncLockBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitSyncLockBlock(node) End If Return node.WithSyncLockStatement(ReplaceStatementIfNeeded(node.SyncLockStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))) End Function Public Overrides Function VisitWithBlock(node As WithBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitWithBlock(node) End If Return node.WithWithStatement(ReplaceStatementIfNeeded(node.WithStatement)). WithStatements(ReplaceStatementsIfNeeded(node.Statements)) End Function Public Overrides Function VisitSingleLineIfStatement(node As SingleLineIfStatementSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitSingleLineIfStatement(node) End If Return SyntaxFactory.SingleLineIfStatement(node.IfKeyword, node.Condition, node.ThenKeyword, VisitList(ReplaceStatementsIfNeeded(node.Statements, colon:=True)), node.ElseClause) End Function Public Overrides Function VisitSingleLineElseClause(node As SingleLineElseClauseSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitSingleLineElseClause(node) End If Return SyntaxFactory.SingleLineElseClause(node.ElseKeyword, VisitList(ReplaceStatementsIfNeeded(node.Statements, colon:=True))) End Function Public Overrides Function VisitMultiLineIfBlock(node As MultiLineIfBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitMultiLineIfBlock(node) End If Return node.WithIfStatement(ReplaceStatementIfNeeded(node.IfStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))) End Function Public Overrides Function VisitElseBlock(node As ElseBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitElseBlock(node) End If Return node.WithElseStatement(ReplaceStatementIfNeeded(node.ElseStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))) End Function Public Overrides Function VisitTryBlock(node As TryBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitTryBlock(node) End If Return node.WithTryStatement(ReplaceStatementIfNeeded(node.TryStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))) End Function Public Overrides Function VisitCatchBlock(node As CatchBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitCatchBlock(node) End If Return node.WithCatchStatement(ReplaceStatementIfNeeded(node.CatchStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))) End Function Public Overrides Function VisitFinallyBlock(node As FinallyBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitFinallyBlock(node) End If Return node.WithFinallyStatement(ReplaceStatementIfNeeded(node.FinallyStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))) End Function Public Overrides Function VisitSelectBlock(node As SelectBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitSelectBlock(node) End If Return node.WithSelectStatement(ReplaceStatementIfNeeded(node.SelectStatement)). WithCaseBlocks(VisitList(node.CaseBlocks)). WithEndSelectStatement(ReplaceStatementIfNeeded(node.EndSelectStatement)) End Function Public Overrides Function VisitCaseBlock(node As CaseBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitCaseBlock(node) End If Return node.WithCaseStatement(ReplaceStatementIfNeeded(node.CaseStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))) End Function Public Overrides Function VisitDoLoopBlock(node As DoLoopBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitDoLoopBlock(node) End If Return node.WithDoStatement(ReplaceStatementIfNeeded(node.DoStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))). WithLoopStatement(ReplaceStatementIfNeeded(node.LoopStatement)) End Function Public Overrides Function VisitForBlock(node As ForBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitForBlock(node) End If Return node.WithForStatement(ReplaceStatementIfNeeded(node.ForStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))). WithNextStatement(ReplaceStatementIfNeeded(node.NextStatement)) End Function Public Overrides Function VisitForEachBlock(node As ForEachBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitForEachBlock(node) End If Return node.WithForEachStatement(ReplaceStatementIfNeeded(node.ForEachStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))). WithNextStatement(ReplaceStatementIfNeeded(node.NextStatement)) End Function Public Overrides Function VisitSingleLineLambdaExpression(node As SingleLineLambdaExpressionSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitSingleLineLambdaExpression(node) End If Dim body = SyntaxFactory.SingletonList(DirectCast(node.Body, StatementSyntax)) Return node.WithBody(VisitList(ReplaceStatementsIfNeeded(body, colon:=True)).First()). WithSubOrFunctionHeader(ReplaceStatementIfNeeded(node.SubOrFunctionHeader)) End Function Public Overrides Function VisitMultiLineLambdaExpression(node As MultiLineLambdaExpressionSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitMultiLineLambdaExpression(node) End If Return node.WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))). WithSubOrFunctionHeader(ReplaceStatementIfNeeded(node.SubOrFunctionHeader)) End Function Private Function ReplaceStatementIfNeeded(Of T As StatementSyntax)(statement As T) As T Contract.ThrowIfNull(statement) ' if all three same If (statement IsNot _firstStatementOrFieldToReplace) OrElse (Me._firstStatementOrFieldToReplace IsNot Me._lastStatementOrFieldToReplace) Then Return statement End If Contract.ThrowIfFalse(Me._statementsOrFieldToInsert.Count() = 1) Return CType(Me._statementsOrFieldToInsert.Single(), T) End Function Private Function ReplaceStatementsIfNeeded(statements As SyntaxList(Of StatementSyntax), Optional colon As Boolean = False) As SyntaxList(Of StatementSyntax) Dim newStatements = New List(Of StatementSyntax)(statements) Dim firstStatementIndex = newStatements.FindIndex(Function(s) s Is Me._firstStatementOrFieldToReplace) ' looks like statements belong to parent's Begin statement. there is nothing we need to do here. If firstStatementIndex < 0 Then Contract.ThrowIfFalse(Me._firstStatementOrFieldToReplace Is Me._lastStatementOrFieldToReplace) Return statements End If Dim lastStatementIndex = newStatements.FindIndex(Function(s) s Is Me._lastStatementOrFieldToReplace) Contract.ThrowIfFalse(lastStatementIndex >= 0) Contract.ThrowIfFalse(firstStatementIndex <= lastStatementIndex) ' okay, this visit contains the statement ' remove statement that must be removed statements = statements.RemoveRange(firstStatementIndex, lastStatementIndex - firstStatementIndex + 1) ' insert new statements Return statements.InsertRange(firstStatementIndex, Join(Me._statementsOrFieldToInsert, colon).ToArray()) End Function Private Shared Function Join(statements As IEnumerable(Of StatementSyntax), colon As Boolean) As IEnumerable(Of StatementSyntax) If Not colon Then Return statements End If Dim removeEndOfLine = Function(t As SyntaxTrivia) Not t.IsElastic() AndAlso t.Kind <> SyntaxKind.EndOfLineTrivia Dim i = 0 Dim count = statements.Count() Dim trivia = SyntaxFactory.ColonTrivia(SyntaxFacts.GetText(SyntaxKind.ColonTrivia)) Dim newStatements = New List(Of StatementSyntax) For Each statement In statements statement = statement.WithLeadingTrivia(statement.GetLeadingTrivia().Where(removeEndOfLine)) If i < count - 1 Then statement = statement.WithTrailingTrivia(statement.GetTrailingTrivia().Where(removeEndOfLine).Concat(trivia)) End If newStatements.Add(statement) i += 1 Next Return newStatements End Function Public Overrides Function VisitModuleBlock(ByVal node As ModuleBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then ' make sure we visit nodes under the block Return MyBase.VisitModuleBlock(node) End If Return node.WithMembers(VisitList(ReplaceStatementsIfNeeded(node.Members))) End Function Public Overrides Function VisitClassBlock(ByVal node As ClassBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then ' make sure we visit nodes under the block Return MyBase.VisitClassBlock(node) End If Return node.WithMembers(VisitList(ReplaceStatementsIfNeeded(node.Members))) End Function Public Overrides Function VisitStructureBlock(ByVal node As StructureBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then ' make sure we visit nodes under the block Return MyBase.VisitStructureBlock(node) End If Return node.WithMembers(VisitList(ReplaceStatementsIfNeeded(node.Members))) End Function Public Overrides Function VisitCompilationUnit(node As CompilationUnitSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then ' make sure we visit nodes under the block Return MyBase.VisitCompilationUnit(node) End If Return node.WithMembers(VisitList(ReplaceStatementsIfNeeded(node.Members))) End Function End Class 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 Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ExtractMethod Partial Friend Class VisualBasicMethodExtractor Partial Private MustInherit Class VisualBasicCodeGenerator Private Class CallSiteContainerRewriter Inherits VisualBasicSyntaxRewriter Private ReadOnly _outmostCallSiteContainer As SyntaxNode Private ReadOnly _statementsOrFieldToInsert As IEnumerable(Of StatementSyntax) Private ReadOnly _variableToRemoveMap As HashSet(Of SyntaxAnnotation) Private ReadOnly _firstStatementOrFieldToReplace As StatementSyntax Private ReadOnly _lastStatementOrFieldToReplace As StatementSyntax Private Shared ReadOnly s_removeAnnotation As SyntaxAnnotation = New SyntaxAnnotation() Public Sub New(outmostCallSiteContainer As SyntaxNode, variableToRemoveMap As HashSet(Of SyntaxAnnotation), firstStatementOrFieldToReplace As StatementSyntax, lastStatementOrFieldToReplace As StatementSyntax, statementsOrFieldToInsert As IEnumerable(Of StatementSyntax)) Contract.ThrowIfNull(outmostCallSiteContainer) Contract.ThrowIfNull(variableToRemoveMap) Contract.ThrowIfNull(firstStatementOrFieldToReplace) Contract.ThrowIfNull(lastStatementOrFieldToReplace) Contract.ThrowIfTrue(statementsOrFieldToInsert.IsEmpty()) Me._outmostCallSiteContainer = outmostCallSiteContainer Me._variableToRemoveMap = variableToRemoveMap Me._statementsOrFieldToInsert = statementsOrFieldToInsert Me._firstStatementOrFieldToReplace = firstStatementOrFieldToReplace Me._lastStatementOrFieldToReplace = lastStatementOrFieldToReplace Contract.ThrowIfFalse(Me._firstStatementOrFieldToReplace.Parent Is Me._lastStatementOrFieldToReplace.Parent) End Sub Public Function Generate() As SyntaxNode Dim result = Visit(Me._outmostCallSiteContainer) ' remove any nodes annotated for removal If result.ContainsAnnotations Then Dim nodesToRemove = result.DescendantNodes(Function(n) n.ContainsAnnotations).Where(Function(n) n.HasAnnotation(s_removeAnnotation)) result = result.RemoveNodes(nodesToRemove, SyntaxRemoveOptions.KeepNoTrivia) End If Return result End Function Private ReadOnly Property ContainerOfStatementsOrFieldToReplace() As SyntaxNode Get Return Me._firstStatementOrFieldToReplace.Parent End Get End Property Public Overrides Function VisitLocalDeclarationStatement(node As LocalDeclarationStatementSyntax) As SyntaxNode node = CType(MyBase.VisitLocalDeclarationStatement(node), LocalDeclarationStatementSyntax) Dim expressionStatements = New List(Of StatementSyntax)() Dim variableDeclarators = New List(Of VariableDeclaratorSyntax)() Dim triviaList = New List(Of SyntaxTrivia)() If Not Me._variableToRemoveMap.ProcessLocalDeclarationStatement(node, expressionStatements, variableDeclarators, triviaList) Then Contract.ThrowIfFalse(expressionStatements.Count = 0) Return node End If Contract.ThrowIfFalse(expressionStatements.Count = 0) If variableDeclarators.Count = 0 AndAlso triviaList.Any(Function(t) t.Kind <> SyntaxKind.WhitespaceTrivia AndAlso t.Kind <> SyntaxKind.EndOfLineTrivia) Then ' well, there are trivia associated with the node. ' we can't just delete the node since then, we will lose ' the trivia. unfortunately, it is not easy to attach the trivia ' to next token. for now, create an empty statement and associate the ' trivia to the statement ' TODO : think about a way to trivia attached to next token Return SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxKind.EmptyToken).WithLeadingTrivia(SyntaxFactory.TriviaList(triviaList))) End If ' return survived var decls If variableDeclarators.Count > 0 Then Return SyntaxFactory.LocalDeclarationStatement( node.Modifiers, SyntaxFactory.SeparatedList(variableDeclarators)).WithPrependedLeadingTrivia(triviaList) End If Return node.WithAdditionalAnnotations(s_removeAnnotation) End Function Public Overrides Function VisitMethodBlock(node As MethodBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then ' make sure we visit nodes under the block Return MyBase.VisitMethodBlock(node) End If Return node.WithSubOrFunctionStatement(ReplaceStatementIfNeeded(node.SubOrFunctionStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))) End Function Public Overrides Function VisitConstructorBlock(node As ConstructorBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then ' make sure we visit nodes under the block Return MyBase.VisitConstructorBlock(node) End If Return node.WithSubNewStatement(ReplaceStatementIfNeeded(node.SubNewStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))) End Function Public Overrides Function VisitOperatorBlock(node As OperatorBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then ' make sure we visit nodes under the block Return MyBase.VisitOperatorBlock(node) End If Return node.WithOperatorStatement(ReplaceStatementIfNeeded(node.OperatorStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))) End Function Public Overrides Function VisitAccessorBlock(node As AccessorBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then ' make sure we visit nodes under the block Return MyBase.VisitAccessorBlock(node) End If Return node.WithAccessorStatement(ReplaceStatementIfNeeded(node.AccessorStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))) End Function Public Overrides Function VisitWhileBlock(node As WhileBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then ' make sure we visit nodes under the switch section Return MyBase.VisitWhileBlock(node) End If Return node.WithWhileStatement(ReplaceStatementIfNeeded(node.WhileStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))) End Function Public Overrides Function VisitUsingBlock(node As UsingBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitUsingBlock(node) End If Return node.WithUsingStatement(ReplaceStatementIfNeeded(node.UsingStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))) End Function Public Overrides Function VisitSyncLockBlock(node As SyncLockBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitSyncLockBlock(node) End If Return node.WithSyncLockStatement(ReplaceStatementIfNeeded(node.SyncLockStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))) End Function Public Overrides Function VisitWithBlock(node As WithBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitWithBlock(node) End If Return node.WithWithStatement(ReplaceStatementIfNeeded(node.WithStatement)). WithStatements(ReplaceStatementsIfNeeded(node.Statements)) End Function Public Overrides Function VisitSingleLineIfStatement(node As SingleLineIfStatementSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitSingleLineIfStatement(node) End If Return SyntaxFactory.SingleLineIfStatement(node.IfKeyword, node.Condition, node.ThenKeyword, VisitList(ReplaceStatementsIfNeeded(node.Statements, colon:=True)), node.ElseClause) End Function Public Overrides Function VisitSingleLineElseClause(node As SingleLineElseClauseSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitSingleLineElseClause(node) End If Return SyntaxFactory.SingleLineElseClause(node.ElseKeyword, VisitList(ReplaceStatementsIfNeeded(node.Statements, colon:=True))) End Function Public Overrides Function VisitMultiLineIfBlock(node As MultiLineIfBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitMultiLineIfBlock(node) End If Return node.WithIfStatement(ReplaceStatementIfNeeded(node.IfStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))) End Function Public Overrides Function VisitElseBlock(node As ElseBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitElseBlock(node) End If Return node.WithElseStatement(ReplaceStatementIfNeeded(node.ElseStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))) End Function Public Overrides Function VisitTryBlock(node As TryBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitTryBlock(node) End If Return node.WithTryStatement(ReplaceStatementIfNeeded(node.TryStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))) End Function Public Overrides Function VisitCatchBlock(node As CatchBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitCatchBlock(node) End If Return node.WithCatchStatement(ReplaceStatementIfNeeded(node.CatchStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))) End Function Public Overrides Function VisitFinallyBlock(node As FinallyBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitFinallyBlock(node) End If Return node.WithFinallyStatement(ReplaceStatementIfNeeded(node.FinallyStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))) End Function Public Overrides Function VisitSelectBlock(node As SelectBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitSelectBlock(node) End If Return node.WithSelectStatement(ReplaceStatementIfNeeded(node.SelectStatement)). WithCaseBlocks(VisitList(node.CaseBlocks)). WithEndSelectStatement(ReplaceStatementIfNeeded(node.EndSelectStatement)) End Function Public Overrides Function VisitCaseBlock(node As CaseBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitCaseBlock(node) End If Return node.WithCaseStatement(ReplaceStatementIfNeeded(node.CaseStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))) End Function Public Overrides Function VisitDoLoopBlock(node As DoLoopBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitDoLoopBlock(node) End If Return node.WithDoStatement(ReplaceStatementIfNeeded(node.DoStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))). WithLoopStatement(ReplaceStatementIfNeeded(node.LoopStatement)) End Function Public Overrides Function VisitForBlock(node As ForBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitForBlock(node) End If Return node.WithForStatement(ReplaceStatementIfNeeded(node.ForStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))). WithNextStatement(ReplaceStatementIfNeeded(node.NextStatement)) End Function Public Overrides Function VisitForEachBlock(node As ForEachBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitForEachBlock(node) End If Return node.WithForEachStatement(ReplaceStatementIfNeeded(node.ForEachStatement)). WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))). WithNextStatement(ReplaceStatementIfNeeded(node.NextStatement)) End Function Public Overrides Function VisitSingleLineLambdaExpression(node As SingleLineLambdaExpressionSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitSingleLineLambdaExpression(node) End If Dim body = SyntaxFactory.SingletonList(DirectCast(node.Body, StatementSyntax)) Return node.WithBody(VisitList(ReplaceStatementsIfNeeded(body, colon:=True)).First()). WithSubOrFunctionHeader(ReplaceStatementIfNeeded(node.SubOrFunctionHeader)) End Function Public Overrides Function VisitMultiLineLambdaExpression(node As MultiLineLambdaExpressionSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then Return MyBase.VisitMultiLineLambdaExpression(node) End If Return node.WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))). WithSubOrFunctionHeader(ReplaceStatementIfNeeded(node.SubOrFunctionHeader)) End Function Private Function ReplaceStatementIfNeeded(Of T As StatementSyntax)(statement As T) As T Contract.ThrowIfNull(statement) ' if all three same If (statement IsNot _firstStatementOrFieldToReplace) OrElse (Me._firstStatementOrFieldToReplace IsNot Me._lastStatementOrFieldToReplace) Then Return statement End If Contract.ThrowIfFalse(Me._statementsOrFieldToInsert.Count() = 1) Return CType(Me._statementsOrFieldToInsert.Single(), T) End Function Private Function ReplaceStatementsIfNeeded(statements As SyntaxList(Of StatementSyntax), Optional colon As Boolean = False) As SyntaxList(Of StatementSyntax) Dim newStatements = New List(Of StatementSyntax)(statements) Dim firstStatementIndex = newStatements.FindIndex(Function(s) s Is Me._firstStatementOrFieldToReplace) ' looks like statements belong to parent's Begin statement. there is nothing we need to do here. If firstStatementIndex < 0 Then Contract.ThrowIfFalse(Me._firstStatementOrFieldToReplace Is Me._lastStatementOrFieldToReplace) Return statements End If Dim lastStatementIndex = newStatements.FindIndex(Function(s) s Is Me._lastStatementOrFieldToReplace) Contract.ThrowIfFalse(lastStatementIndex >= 0) Contract.ThrowIfFalse(firstStatementIndex <= lastStatementIndex) ' okay, this visit contains the statement ' remove statement that must be removed statements = statements.RemoveRange(firstStatementIndex, lastStatementIndex - firstStatementIndex + 1) ' insert new statements Return statements.InsertRange(firstStatementIndex, Join(Me._statementsOrFieldToInsert, colon).ToArray()) End Function Private Shared Function Join(statements As IEnumerable(Of StatementSyntax), colon As Boolean) As IEnumerable(Of StatementSyntax) If Not colon Then Return statements End If Dim removeEndOfLine = Function(t As SyntaxTrivia) Not t.IsElastic() AndAlso t.Kind <> SyntaxKind.EndOfLineTrivia Dim i = 0 Dim count = statements.Count() Dim trivia = SyntaxFactory.ColonTrivia(SyntaxFacts.GetText(SyntaxKind.ColonTrivia)) Dim newStatements = New List(Of StatementSyntax) For Each statement In statements statement = statement.WithLeadingTrivia(statement.GetLeadingTrivia().Where(removeEndOfLine)) If i < count - 1 Then statement = statement.WithTrailingTrivia(statement.GetTrailingTrivia().Where(removeEndOfLine).Concat(trivia)) End If newStatements.Add(statement) i += 1 Next Return newStatements End Function Public Overrides Function VisitModuleBlock(ByVal node As ModuleBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then ' make sure we visit nodes under the block Return MyBase.VisitModuleBlock(node) End If Return node.WithMembers(VisitList(ReplaceStatementsIfNeeded(node.Members))) End Function Public Overrides Function VisitClassBlock(ByVal node As ClassBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then ' make sure we visit nodes under the block Return MyBase.VisitClassBlock(node) End If Return node.WithMembers(VisitList(ReplaceStatementsIfNeeded(node.Members))) End Function Public Overrides Function VisitStructureBlock(ByVal node As StructureBlockSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then ' make sure we visit nodes under the block Return MyBase.VisitStructureBlock(node) End If Return node.WithMembers(VisitList(ReplaceStatementsIfNeeded(node.Members))) End Function Public Overrides Function VisitCompilationUnit(node As CompilationUnitSyntax) As SyntaxNode If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then ' make sure we visit nodes under the block Return MyBase.VisitCompilationUnit(node) End If Return node.WithMembers(VisitList(ReplaceStatementsIfNeeded(node.Members))) End Function End Class End Class End Class End Namespace
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Analyzers/Core/Analyzers/UseCompoundAssignment/UseCompoundAssignmentUtilities.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.LanguageServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UseCompoundAssignment { internal static class UseCompoundAssignmentUtilities { internal const string Increment = nameof(Increment); internal const string Decrement = nameof(Decrement); public static void GenerateMaps<TSyntaxKind>( ImmutableArray<(TSyntaxKind exprKind, TSyntaxKind assignmentKind, TSyntaxKind tokenKind)> kinds, out ImmutableDictionary<TSyntaxKind, TSyntaxKind> binaryToAssignmentMap, out ImmutableDictionary<TSyntaxKind, TSyntaxKind> assignmentToTokenMap) { var binaryToAssignmentBuilder = ImmutableDictionary.CreateBuilder<TSyntaxKind, TSyntaxKind>(); var assignmentToTokenBuilder = ImmutableDictionary.CreateBuilder<TSyntaxKind, TSyntaxKind>(); foreach (var (exprKind, assignmentKind, tokenKind) in kinds) { binaryToAssignmentBuilder[exprKind] = assignmentKind; assignmentToTokenBuilder[assignmentKind] = tokenKind; } binaryToAssignmentMap = binaryToAssignmentBuilder.ToImmutable(); assignmentToTokenMap = assignmentToTokenBuilder.ToImmutable(); Debug.Assert(binaryToAssignmentMap.Count == assignmentToTokenMap.Count); Debug.Assert(binaryToAssignmentMap.Values.All(assignmentToTokenMap.ContainsKey)); } public static bool IsSideEffectFree( ISyntaxFacts syntaxFacts, SyntaxNode expr, SemanticModel semanticModel, CancellationToken cancellationToken) { return IsSideEffectFreeRecurse(syntaxFacts, expr, semanticModel, isTopLevel: true, cancellationToken); } private static bool IsSideEffectFreeRecurse( ISyntaxFacts syntaxFacts, SyntaxNode expr, SemanticModel semanticModel, bool isTopLevel, CancellationToken cancellationToken) { if (expr == null) { return false; } // it basically has to be of the form "a.b.c", where all components are locals, // parameters or fields. Basically, nothing that can cause arbitrary user code // execution when being evaluated by the compiler. if (syntaxFacts.IsThisExpression(expr) || syntaxFacts.IsBaseExpression(expr)) { // Referencing this/base like this.a.b.c causes no side effects itself. return true; } if (syntaxFacts.IsIdentifierName(expr)) { return IsSideEffectFreeSymbol(expr, semanticModel, isTopLevel, cancellationToken); } if (syntaxFacts.IsParenthesizedExpression(expr)) { syntaxFacts.GetPartsOfParenthesizedExpression(expr, out _, out var expression, out _); return IsSideEffectFreeRecurse(syntaxFacts, expression, semanticModel, isTopLevel, cancellationToken); } if (syntaxFacts.IsSimpleMemberAccessExpression(expr)) { syntaxFacts.GetPartsOfMemberAccessExpression(expr, out var subExpr, out _); return IsSideEffectFreeRecurse(syntaxFacts, subExpr, semanticModel, isTopLevel: false, cancellationToken) && IsSideEffectFreeSymbol(expr, semanticModel, isTopLevel, cancellationToken); } if (syntaxFacts.IsConditionalAccessExpression(expr)) { syntaxFacts.GetPartsOfConditionalAccessExpression(expr, out var expression, out var whenNotNull); return IsSideEffectFreeRecurse(syntaxFacts, expression, semanticModel, isTopLevel: false, cancellationToken) && IsSideEffectFreeRecurse(syntaxFacts, whenNotNull, semanticModel, isTopLevel: false, cancellationToken); } // Something we don't explicitly handle. Assume this may have side effects. return false; } private static bool IsSideEffectFreeSymbol( SyntaxNode expr, SemanticModel semanticModel, bool isTopLevel, CancellationToken cancellationToken) { var symbolInfo = semanticModel.GetSymbolInfo(expr, cancellationToken); if (symbolInfo.CandidateSymbols.Length > 0 || symbolInfo.Symbol == null) { // couldn't bind successfully, assume that this might have side-effects. return false; } var symbol = symbolInfo.Symbol; switch (symbol.Kind) { case SymbolKind.Namespace: case SymbolKind.NamedType: case SymbolKind.Field: case SymbolKind.Parameter: case SymbolKind.Local: return true; } if (symbol.Kind == SymbolKind.Property && isTopLevel) { // If we have `this.Prop = this.Prop * 2`, then that's just a single read/write of // the prop and we can safely make that `this.Prop *= 2` (since it will still be a // single read/write). However, if we had `this.prop.x = this.prop.x * 2`, then // that's multiple reads of `this.prop`, and it's not safe to convert that to // `this.prop.x *= 2` in the case where calling 'prop' may have side effects. // // Note, this doesn't apply if the property is a ref-property. In that case, we'd // go from a read and a write to to just a read (and a write to it's returned ref // value). var property = (IPropertySymbol)symbol; if (property.RefKind == RefKind.None) { return true; } } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.LanguageServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UseCompoundAssignment { internal static class UseCompoundAssignmentUtilities { internal const string Increment = nameof(Increment); internal const string Decrement = nameof(Decrement); public static void GenerateMaps<TSyntaxKind>( ImmutableArray<(TSyntaxKind exprKind, TSyntaxKind assignmentKind, TSyntaxKind tokenKind)> kinds, out ImmutableDictionary<TSyntaxKind, TSyntaxKind> binaryToAssignmentMap, out ImmutableDictionary<TSyntaxKind, TSyntaxKind> assignmentToTokenMap) { var binaryToAssignmentBuilder = ImmutableDictionary.CreateBuilder<TSyntaxKind, TSyntaxKind>(); var assignmentToTokenBuilder = ImmutableDictionary.CreateBuilder<TSyntaxKind, TSyntaxKind>(); foreach (var (exprKind, assignmentKind, tokenKind) in kinds) { binaryToAssignmentBuilder[exprKind] = assignmentKind; assignmentToTokenBuilder[assignmentKind] = tokenKind; } binaryToAssignmentMap = binaryToAssignmentBuilder.ToImmutable(); assignmentToTokenMap = assignmentToTokenBuilder.ToImmutable(); Debug.Assert(binaryToAssignmentMap.Count == assignmentToTokenMap.Count); Debug.Assert(binaryToAssignmentMap.Values.All(assignmentToTokenMap.ContainsKey)); } public static bool IsSideEffectFree( ISyntaxFacts syntaxFacts, SyntaxNode expr, SemanticModel semanticModel, CancellationToken cancellationToken) { return IsSideEffectFreeRecurse(syntaxFacts, expr, semanticModel, isTopLevel: true, cancellationToken); } private static bool IsSideEffectFreeRecurse( ISyntaxFacts syntaxFacts, SyntaxNode expr, SemanticModel semanticModel, bool isTopLevel, CancellationToken cancellationToken) { if (expr == null) { return false; } // it basically has to be of the form "a.b.c", where all components are locals, // parameters or fields. Basically, nothing that can cause arbitrary user code // execution when being evaluated by the compiler. if (syntaxFacts.IsThisExpression(expr) || syntaxFacts.IsBaseExpression(expr)) { // Referencing this/base like this.a.b.c causes no side effects itself. return true; } if (syntaxFacts.IsIdentifierName(expr)) { return IsSideEffectFreeSymbol(expr, semanticModel, isTopLevel, cancellationToken); } if (syntaxFacts.IsParenthesizedExpression(expr)) { syntaxFacts.GetPartsOfParenthesizedExpression(expr, out _, out var expression, out _); return IsSideEffectFreeRecurse(syntaxFacts, expression, semanticModel, isTopLevel, cancellationToken); } if (syntaxFacts.IsSimpleMemberAccessExpression(expr)) { syntaxFacts.GetPartsOfMemberAccessExpression(expr, out var subExpr, out _); return IsSideEffectFreeRecurse(syntaxFacts, subExpr, semanticModel, isTopLevel: false, cancellationToken) && IsSideEffectFreeSymbol(expr, semanticModel, isTopLevel, cancellationToken); } if (syntaxFacts.IsConditionalAccessExpression(expr)) { syntaxFacts.GetPartsOfConditionalAccessExpression(expr, out var expression, out var whenNotNull); return IsSideEffectFreeRecurse(syntaxFacts, expression, semanticModel, isTopLevel: false, cancellationToken) && IsSideEffectFreeRecurse(syntaxFacts, whenNotNull, semanticModel, isTopLevel: false, cancellationToken); } // Something we don't explicitly handle. Assume this may have side effects. return false; } private static bool IsSideEffectFreeSymbol( SyntaxNode expr, SemanticModel semanticModel, bool isTopLevel, CancellationToken cancellationToken) { var symbolInfo = semanticModel.GetSymbolInfo(expr, cancellationToken); if (symbolInfo.CandidateSymbols.Length > 0 || symbolInfo.Symbol == null) { // couldn't bind successfully, assume that this might have side-effects. return false; } var symbol = symbolInfo.Symbol; switch (symbol.Kind) { case SymbolKind.Namespace: case SymbolKind.NamedType: case SymbolKind.Field: case SymbolKind.Parameter: case SymbolKind.Local: return true; } if (symbol.Kind == SymbolKind.Property && isTopLevel) { // If we have `this.Prop = this.Prop * 2`, then that's just a single read/write of // the prop and we can safely make that `this.Prop *= 2` (since it will still be a // single read/write). However, if we had `this.prop.x = this.prop.x * 2`, then // that's multiple reads of `this.prop`, and it's not safe to convert that to // `this.prop.x *= 2` in the case where calling 'prop' may have side effects. // // Note, this doesn't apply if the property is a ref-property. In that case, we'd // go from a read and a write to to just a read (and a write to it's returned ref // value). var property = (IPropertySymbol)symbol; if (property.RefKind == RefKind.None) { return true; } } return false; } } }
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharpTest/CodeGeneration/AddImportsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Editing { [UseExportProvider] public class AddImportsTests { private static async Task<Document> GetDocument(string code, bool withAnnotations) { var ws = new AdhocWorkspace(); var emptyProject = ws.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Default, "test", "test.dll", LanguageNames.CSharp, metadataReferences: new[] { TestMetadata.Net451.mscorlib })); var doc = emptyProject.AddDocument("test.cs", code); if (withAnnotations) { var root = await doc.GetSyntaxRootAsync(); var model = await doc.GetSemanticModelAsync(); root = root.ReplaceNodes(root.DescendantNodesAndSelf().OfType<TypeSyntax>(), (o, c) => { var symbol = model.GetSymbolInfo(o).Symbol; return symbol != null ? c.WithAdditionalAnnotations(SymbolAnnotation.Create(symbol), Simplifier.Annotation) : c; }); doc = doc.WithSyntaxRoot(root); } return doc; } private static Task TestNoImportsAddedAsync( string initialText, bool useSymbolAnnotations, Func<OptionSet, OptionSet> optionsTransform = null) { return TestAsync(initialText, initialText, initialText, useSymbolAnnotations, optionsTransform, performCheck: false); } private static async Task TestAsync( string initialText, string importsAddedText, string simplifiedText, bool useSymbolAnnotations, Func<OptionSet, OptionSet> optionsTransform = null, bool performCheck = true) { var doc = await GetDocument(initialText, useSymbolAnnotations); OptionSet options = await doc.GetOptionsAsync(); if (optionsTransform != null) { options = optionsTransform(options); } var imported = useSymbolAnnotations ? await ImportAdder.AddImportsFromSymbolAnnotationAsync(doc, options) : await ImportAdder.AddImportsFromSyntaxesAsync(doc, options); if (importsAddedText != null) { var formatted = await Formatter.FormatAsync(imported, SyntaxAnnotation.ElasticAnnotation, options); var actualText = (await formatted.GetTextAsync()).ToString(); Assert.Equal(importsAddedText, actualText); } if (simplifiedText != null) { var reduced = await Simplifier.ReduceAsync(imported, options); var formatted = await Formatter.FormatAsync(reduced, SyntaxAnnotation.ElasticAnnotation, options); var actualText = (await formatted.GetTextAsync()).ToString(); Assert.Equal(simplifiedText, actualText); } if (performCheck) { if (initialText == importsAddedText && importsAddedText == simplifiedText) throw new Exception($"use {nameof(TestNoImportsAddedAsync)}"); } } public static object[][] TestAllData = { new object[] { false }, new object[] { true }, }; [Theory, MemberData(nameof(TestAllData))] public async Task TestAddImport(bool useSymbolAnnotations) { await TestAsync( @"class C { public System.Collections.Generic.List<int> F; }", @"using System.Collections.Generic; class C { public System.Collections.Generic.List<int> F; }", @"using System.Collections.Generic; class C { public List<int> F; }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] public async Task TestAddSystemImportFirst(bool useSymbolAnnotations) { await TestAsync( @"using N; class C { public System.Collections.Generic.List<int> F; }", @"using System.Collections.Generic; using N; class C { public System.Collections.Generic.List<int> F; }", @"using System.Collections.Generic; using N; class C { public List<int> F; }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] public async Task TestDontAddSystemImportFirst(bool useSymbolAnnotations) { await TestAsync( @"using N; class C { public System.Collections.Generic.List<int> F; }", @"using N; using System.Collections.Generic; class C { public System.Collections.Generic.List<int> F; }", @"using N; using System.Collections.Generic; class C { public List<int> F; }", useSymbolAnnotations, options => options.WithChangedOption(GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp, false) ); } [Theory, MemberData(nameof(TestAllData))] public async Task TestAddImportsInOrder(bool useSymbolAnnotations) { await TestAsync( @"using System.Collections; using System.Diagnostics; class C { public System.Collections.Generic.List<int> F; }", @"using System.Collections; using System.Collections.Generic; using System.Diagnostics; class C { public System.Collections.Generic.List<int> F; }", @"using System.Collections; using System.Collections.Generic; using System.Diagnostics; class C { public List<int> F; }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] public async Task TestAddMultipleImportsInOrder(bool useSymbolAnnotations) { await TestAsync( @"class C { public System.Collections.Generic.List<int> F; public System.EventHandler Handler; }", @"using System; using System.Collections.Generic; class C { public System.Collections.Generic.List<int> F; public System.EventHandler Handler; }", @"using System; using System.Collections.Generic; class C { public List<int> F; public EventHandler Handler; }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] public async Task TestImportNotRedundantlyAdded(bool useSymbolAnnotations) { await TestAsync( @"using System.Collections.Generic; class C { public System.Collections.Generic.List<int> F; }", @"using System.Collections.Generic; class C { public System.Collections.Generic.List<int> F; }", @"using System.Collections.Generic; class C { public List<int> F; }", useSymbolAnnotations); } [Fact] public async Task TestBuiltInTypeFromSyntaxes() { await TestAsync( @"class C { public System.Int32 F; }", @"using System; class C { public System.Int32 F; }", @"class C { public int F; }", useSymbolAnnotations: false); } [Fact] public async Task TestBuiltInTypeFromSymbols() { await TestAsync( @"class C { public System.Int32 F; }", @"class C { public System.Int32 F; }", @"class C { public int F; }", useSymbolAnnotations: true); } [Theory, MemberData(nameof(TestAllData))] public async Task TestImportNotAddedForNamespaceDeclarations(bool useSymbolAnnotations) { await TestNoImportsAddedAsync( @"namespace N { }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] public async Task TestImportNotAddedForReferencesInsideNamespaceDeclarations(bool useSymbolAnnotations) { await TestAsync( @"namespace N { class C { private N.C c; } }", @"namespace N { class C { private N.C c; } }", @"namespace N { class C { private C c; } }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] public async Task TestImportNotAddedForReferencesInsideParentOfNamespaceDeclarations(bool useSymbolAnnotations) { await TestAsync( @"namespace N { class C { } } namespace N.N1 { class C1 { private N.C c; } }", @"namespace N { class C { } } namespace N.N1 { class C1 { private N.C c; } }", @"namespace N { class C { } } namespace N.N1 { class C1 { private C c; } }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] public async Task TestImportNotAddedForReferencesMatchingNestedImports(bool useSymbolAnnotations) { await TestAsync( @"namespace N { using System.Collections.Generic; class C { private System.Collections.Generic.List<int> F; } }", @"namespace N { using System.Collections.Generic; class C { private System.Collections.Generic.List<int> F; } }", @"namespace N { using System.Collections.Generic; class C { private List<int> F; } }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] public async Task TestImportRemovedIfItMakesReferenceAmbiguous(bool useSymbolAnnotations) { // this is not really an artifact of the AddImports feature, it is due // to Simplifier not reducing the namespace reference because it would // become ambiguous, thus leaving an unused using directive await TestAsync( @"namespace N { class C { } } class C { public N.C F; }", @"using N; namespace N { class C { } } class C { public N.C F; }", @"namespace N { class C { } } class C { public N.C F; }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] [WorkItem(8797, "https://github.com/dotnet/roslyn/issues/8797")] public async Task TestBannerTextRemainsAtTopOfDocumentWithoutExistingImports(bool useSymbolAnnotations) { await TestAsync( @"// -------------------------------------------------------------------------------------------------------------------- // <copyright file=""File.cs"" company=""MyOrgnaization""> // Copyright (C) MyOrgnaization 2016 // </copyright> // -------------------------------------------------------------------------------------------------------------------- class C { public System.Collections.Generic.List<int> F; }", @"// -------------------------------------------------------------------------------------------------------------------- // <copyright file=""File.cs"" company=""MyOrgnaization""> // Copyright (C) MyOrgnaization 2016 // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System.Collections.Generic; class C { public System.Collections.Generic.List<int> F; }", @"// -------------------------------------------------------------------------------------------------------------------- // <copyright file=""File.cs"" company=""MyOrgnaization""> // Copyright (C) MyOrgnaization 2016 // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System.Collections.Generic; class C { public List<int> F; }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] [WorkItem(8797, "https://github.com/dotnet/roslyn/issues/8797")] public async Task TestBannerTextRemainsAtTopOfDocumentWithExistingImports(bool useSymbolAnnotations) { await TestAsync( @"// -------------------------------------------------------------------------------------------------------------------- // <copyright file=""File.cs"" company=""MyOrgnaization""> // Copyright (C) MyOrgnaization 2016 // </copyright> // -------------------------------------------------------------------------------------------------------------------- using ZZZ; class C { public System.Collections.Generic.List<int> F; }", @"// -------------------------------------------------------------------------------------------------------------------- // <copyright file=""File.cs"" company=""MyOrgnaization""> // Copyright (C) MyOrgnaization 2016 // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System.Collections.Generic; using ZZZ; class C { public System.Collections.Generic.List<int> F; }", @"// -------------------------------------------------------------------------------------------------------------------- // <copyright file=""File.cs"" company=""MyOrgnaization""> // Copyright (C) MyOrgnaization 2016 // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System.Collections.Generic; using ZZZ; class C { public List<int> F; }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] [WorkItem(8797, "https://github.com/dotnet/roslyn/issues/8797")] public async Task TestLeadingWhitespaceLinesArePreserved(bool useSymbolAnnotations) { await TestAsync( @"class C { public System.Collections.Generic.List<int> F; }", @"using System.Collections.Generic; class C { public System.Collections.Generic.List<int> F; }", @"using System.Collections.Generic; class C { public List<int> F; }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] public async Task TestImportAddedToNestedImports(bool useSymbolAnnotations) { await TestAsync( @"namespace N { using System; class C { private System.Collections.Generic.List<int> F; } }", @"namespace N { using System; using System.Collections.Generic; class C { private System.Collections.Generic.List<int> F; } }", @"namespace N { using System; using System.Collections.Generic; class C { private List<int> F; } }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] public async Task TestImportNameNotSimplfied(bool useSymbolAnnotations) { await TestAsync( @"namespace System { using System.Threading; class C { private System.Collections.Generic.List<int> F; } }", @"namespace System { using System.Collections.Generic; using System.Threading; class C { private System.Collections.Generic.List<int> F; } }", @"namespace System { using System.Collections.Generic; using System.Threading; class C { private List<int> F; } }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] public async Task TestUnnecessaryImportAddedAndRemoved(bool useSymbolAnnotations) { await TestAsync( @"using List = System.Collections.Generic.List<int>; namespace System { class C { private List F; } }", @"using System.Collections.Generic; using List = System.Collections.Generic.List<int>; namespace System { class C { private List F; } }", @"using List = System.Collections.Generic.List<int>; namespace System { class C { private List F; } }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] public async Task TestImportAddedToStartOfDocumentIfNoNestedImports(bool useSymbolAnnotations) { await TestAsync( @"namespace N { class C { private System.Collections.Generic.List<int> F; } }", @"using System.Collections.Generic; namespace N { class C { private System.Collections.Generic.List<int> F; } }", @"using System.Collections.Generic; namespace N { class C { private List<int> F; } }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] [WorkItem(9228, "https://github.com/dotnet/roslyn/issues/9228")] public async Task TestDoNotAddDuplicateImportIfNamespaceIsDefinedInSourceAndExternalAssembly(bool useSymbolAnnotations) { var externalCode = @"namespace N.M { public class A : System.Attribute { } }"; var code = @"using System; using N.M; class C { public void M1(String p1) { } public void M2([A] String p2) { } }"; var otherAssemblyReference = GetInMemoryAssemblyReferenceForCode(externalCode); var ws = new AdhocWorkspace(); var emptyProject = ws.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Default, "test", "test.dll", LanguageNames.CSharp, metadataReferences: new[] { TestMetadata.Net451.mscorlib })); var project = emptyProject .AddMetadataReferences(new[] { otherAssemblyReference }) .WithCompilationOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); project = project.AddDocument("duplicate.cs", externalCode).Project; var document = project.AddDocument("test.cs", code); var options = document.Project.Solution.Workspace.Options; var compilation = await document.Project.GetCompilationAsync(CancellationToken.None); var compilerDiagnostics = compilation.GetDiagnostics(CancellationToken.None); Assert.Empty(compilerDiagnostics.Where(d => d.Severity == DiagnosticSeverity.Error)); var attribute = compilation.GetTypeByMetadataName("N.M.A"); var syntaxRoot = await document.GetSyntaxRootAsync(CancellationToken.None).ConfigureAwait(false); SyntaxNode p1SyntaxNode = syntaxRoot.DescendantNodes().OfType<ParameterSyntax>().FirstOrDefault(); // Add N.M.A attribute to p1. var editor = await DocumentEditor.CreateAsync(document, CancellationToken.None).ConfigureAwait(false); var attributeSyntax = editor.Generator.Attribute(editor.Generator.TypeExpression(attribute)); editor.AddAttribute(p1SyntaxNode, attributeSyntax); var documentWithAttribute = editor.GetChangedDocument(); // Add namespace import. var imported = useSymbolAnnotations ? await ImportAdder.AddImportsFromSymbolAnnotationAsync(documentWithAttribute, null, CancellationToken.None).ConfigureAwait(false) : await ImportAdder.AddImportsFromSyntaxesAsync(documentWithAttribute, null, CancellationToken.None).ConfigureAwait(false); var formatted = await Formatter.FormatAsync(imported, options); var actualText = (await formatted.GetTextAsync()).ToString(); Assert.Equal(@"using System; using N.M; class C { public void M1([global::N.M.A] String p1) { } public void M2([A] String p2) { } }", actualText); } private static MetadataReference GetInMemoryAssemblyReferenceForCode(string code) { var tree = CSharpSyntaxTree.ParseText(code); var compilation = CSharpCompilation .Create("test.dll", new[] { tree }) .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) .AddReferences(TestMetadata.Net451.mscorlib); return compilation.ToMetadataReference(); } #region AddImports Safe Tests [Fact] public async Task TestSafeWithMatchingSimpleName() { await TestNoImportsAddedAsync( @"using B; namespace A { class C1 {} class C2 {} } namespace B { class C1 {} } class C { C1 M(A.C2 c2) => default; }", useSymbolAnnotations: true); } [Fact] public async Task TestSafeWithMatchingGenericName() { await TestNoImportsAddedAsync( @"using B; namespace A { class C1<T> {} class C2 {} } namespace B { class C1<T> {} } class C { C1<int> M(A.C2 c2) => default; }", useSymbolAnnotations: true); } [Fact] public async Task TestSafeWithMatchingQualifiedName() { await TestNoImportsAddedAsync( @"using B; namespace A { class O {} class C2 {} } namespace B { class O { public class C1 {} } } class C { O.C1 M(A.C2 c2) => default; }", useSymbolAnnotations: true); } [Fact] public async Task TestSafeWithMatchingAliasedIdentifierName() { await TestNoImportsAddedAsync( @"using C1 = B.C1; namespace A { class C1 {} class C2 {} } namespace B { class C1 {} } namespace Inner { class C { C1 M(A.C2 c2) => default; } }", useSymbolAnnotations: true); } [Fact] public async Task TestSafeWithMatchingGenericNameAndTypeArguments() { await TestNoImportsAddedAsync( @"using B; namespace A { class C1<T> {} class C2 {} class C3 {} } namespace B { class C1<T> {} class C3 {} } class C { C1<C3> M(A.C2 c2) => default; }", useSymbolAnnotations: true); } [Fact] public async Task TestSafeWithMatchingGenericNameAndTypeArguments_DifferentArity() { await TestAsync( @"using B; namespace A { class C1<T, X> {} class C2 {} } namespace B { class C1<T> {} class C3 {} } class C { C1<C3> M(A.C2 c2) => default; }", @"using A; using B; namespace A { class C1<T, X> {} class C2 {} } namespace B { class C1<T> {} class C3 {} } class C { C1<C3> M(A.C2 c2) => default; }", @"using A; using B; namespace A { class C1<T, X> {} class C2 {} } namespace B { class C1<T> {} class C3 {} } class C { C1<C3> M(C2 c2) => default; }", useSymbolAnnotations: true); } [Fact] public async Task TestSafeWithMatchingQualifiedNameAndTypeArguments() { await TestNoImportsAddedAsync( @"using B; namespace A { class O {} class C2 {} class C3 {} } namespace B { class C3 {} class O { public class C1<T> {} } } class C { O.C1<C3> M(A.C2 c2) => default; }", useSymbolAnnotations: true); } [Fact, WorkItem(39641, "https://github.com/dotnet/roslyn/issues/39641")] public async Task TestSafeWithMatchingSimpleNameInAllLocations() { await TestNoImportsAddedAsync( @"using B; using System.Collections.Generic; namespace A { class C1 { } class C2 { } } namespace B { class C1 { public static C1 P { get; } } } #nullable enable #pragma warning disable class C { /// <summary> /// <see cref=""C1""/> /// </summary> C1 M(C1 c1, A.C2 c2) { C1 result = (C1)c1 ?? new C1() ?? C1.P ?? new C1[0] { }[0] ?? new List<C1>()[0] ?? (C1?)null; (C1 a, int b) = (default, default); return result; } }", useSymbolAnnotations: true); } [Fact] public async Task TestSafeWithMatchingExtensionMethod() { await TestNoImportsAddedAsync( @"using B; namespace A { static class AExtensions { public static void M(this int a){} } public class C1 {} } namespace B { static class BExtensions { public static void M(this int a){} } } class C { void M(A.C1 c1) => 42.M(); }", useSymbolAnnotations: true); } [Fact] public async Task TestSafeWithMatchingExtensionMethodAndArguments() { await TestNoImportsAddedAsync( @"using B; namespace A { static class AExtensions { public static void M(this int a, C2 c2){} } public class C1 {} public class C2 {} } namespace B { static class BExtensions { public static void M(this int a, C2 c2){} } public class C2 {} } class C { void M(A.C1 c1) => 42.M(default(C2)); }", useSymbolAnnotations: true); } [Fact] public async Task TestSafeWithMatchingExtensionMethodAndTypeArguments() { await TestNoImportsAddedAsync( @"using B; namespace A { static class AExtensions { public static void M<T>(this int a){} } public class C1 {} public class C2 {} } namespace B { static class BExtensions { public static void M<T>(this int a){} } public class C2 {} } class C { void M(A.C1 c1) => 42.M<C2>(); }", useSymbolAnnotations: true); } [Fact] public async Task TestSafeWithLambdaExtensionMethodAmbiguity() { await TestNoImportsAddedAsync( @"using System; class C { // Don't add a using for N even though it is used here. public N.Other x; public static void Main() { M(x => x.M1()); } public static void M(Action<C> a){} public static void M(Action<int> a){} public void M1(){} } namespace N { public class Other { } public static class Extensions { public static void M1(this int a){} } }", useSymbolAnnotations: true); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Editing { [UseExportProvider] public class AddImportsTests { private static async Task<Document> GetDocument(string code, bool withAnnotations) { var ws = new AdhocWorkspace(); var emptyProject = ws.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Default, "test", "test.dll", LanguageNames.CSharp, metadataReferences: new[] { TestMetadata.Net451.mscorlib })); var doc = emptyProject.AddDocument("test.cs", code); if (withAnnotations) { var root = await doc.GetSyntaxRootAsync(); var model = await doc.GetSemanticModelAsync(); root = root.ReplaceNodes(root.DescendantNodesAndSelf().OfType<TypeSyntax>(), (o, c) => { var symbol = model.GetSymbolInfo(o).Symbol; return symbol != null ? c.WithAdditionalAnnotations(SymbolAnnotation.Create(symbol), Simplifier.Annotation) : c; }); doc = doc.WithSyntaxRoot(root); } return doc; } private static Task TestNoImportsAddedAsync( string initialText, bool useSymbolAnnotations, Func<OptionSet, OptionSet> optionsTransform = null) { return TestAsync(initialText, initialText, initialText, useSymbolAnnotations, optionsTransform, performCheck: false); } private static async Task TestAsync( string initialText, string importsAddedText, string simplifiedText, bool useSymbolAnnotations, Func<OptionSet, OptionSet> optionsTransform = null, bool performCheck = true) { var doc = await GetDocument(initialText, useSymbolAnnotations); OptionSet options = await doc.GetOptionsAsync(); if (optionsTransform != null) { options = optionsTransform(options); } var imported = useSymbolAnnotations ? await ImportAdder.AddImportsFromSymbolAnnotationAsync(doc, options) : await ImportAdder.AddImportsFromSyntaxesAsync(doc, options); if (importsAddedText != null) { var formatted = await Formatter.FormatAsync(imported, SyntaxAnnotation.ElasticAnnotation, options); var actualText = (await formatted.GetTextAsync()).ToString(); Assert.Equal(importsAddedText, actualText); } if (simplifiedText != null) { var reduced = await Simplifier.ReduceAsync(imported, options); var formatted = await Formatter.FormatAsync(reduced, SyntaxAnnotation.ElasticAnnotation, options); var actualText = (await formatted.GetTextAsync()).ToString(); Assert.Equal(simplifiedText, actualText); } if (performCheck) { if (initialText == importsAddedText && importsAddedText == simplifiedText) throw new Exception($"use {nameof(TestNoImportsAddedAsync)}"); } } public static object[][] TestAllData = { new object[] { false }, new object[] { true }, }; [Theory, MemberData(nameof(TestAllData))] public async Task TestAddImport(bool useSymbolAnnotations) { await TestAsync( @"class C { public System.Collections.Generic.List<int> F; }", @"using System.Collections.Generic; class C { public System.Collections.Generic.List<int> F; }", @"using System.Collections.Generic; class C { public List<int> F; }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] public async Task TestAddSystemImportFirst(bool useSymbolAnnotations) { await TestAsync( @"using N; class C { public System.Collections.Generic.List<int> F; }", @"using System.Collections.Generic; using N; class C { public System.Collections.Generic.List<int> F; }", @"using System.Collections.Generic; using N; class C { public List<int> F; }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] public async Task TestDontAddSystemImportFirst(bool useSymbolAnnotations) { await TestAsync( @"using N; class C { public System.Collections.Generic.List<int> F; }", @"using N; using System.Collections.Generic; class C { public System.Collections.Generic.List<int> F; }", @"using N; using System.Collections.Generic; class C { public List<int> F; }", useSymbolAnnotations, options => options.WithChangedOption(GenerationOptions.PlaceSystemNamespaceFirst, LanguageNames.CSharp, false) ); } [Theory, MemberData(nameof(TestAllData))] public async Task TestAddImportsInOrder(bool useSymbolAnnotations) { await TestAsync( @"using System.Collections; using System.Diagnostics; class C { public System.Collections.Generic.List<int> F; }", @"using System.Collections; using System.Collections.Generic; using System.Diagnostics; class C { public System.Collections.Generic.List<int> F; }", @"using System.Collections; using System.Collections.Generic; using System.Diagnostics; class C { public List<int> F; }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] public async Task TestAddMultipleImportsInOrder(bool useSymbolAnnotations) { await TestAsync( @"class C { public System.Collections.Generic.List<int> F; public System.EventHandler Handler; }", @"using System; using System.Collections.Generic; class C { public System.Collections.Generic.List<int> F; public System.EventHandler Handler; }", @"using System; using System.Collections.Generic; class C { public List<int> F; public EventHandler Handler; }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] public async Task TestImportNotRedundantlyAdded(bool useSymbolAnnotations) { await TestAsync( @"using System.Collections.Generic; class C { public System.Collections.Generic.List<int> F; }", @"using System.Collections.Generic; class C { public System.Collections.Generic.List<int> F; }", @"using System.Collections.Generic; class C { public List<int> F; }", useSymbolAnnotations); } [Fact] public async Task TestBuiltInTypeFromSyntaxes() { await TestAsync( @"class C { public System.Int32 F; }", @"using System; class C { public System.Int32 F; }", @"class C { public int F; }", useSymbolAnnotations: false); } [Fact] public async Task TestBuiltInTypeFromSymbols() { await TestAsync( @"class C { public System.Int32 F; }", @"class C { public System.Int32 F; }", @"class C { public int F; }", useSymbolAnnotations: true); } [Theory, MemberData(nameof(TestAllData))] public async Task TestImportNotAddedForNamespaceDeclarations(bool useSymbolAnnotations) { await TestNoImportsAddedAsync( @"namespace N { }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] public async Task TestImportNotAddedForReferencesInsideNamespaceDeclarations(bool useSymbolAnnotations) { await TestAsync( @"namespace N { class C { private N.C c; } }", @"namespace N { class C { private N.C c; } }", @"namespace N { class C { private C c; } }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] public async Task TestImportNotAddedForReferencesInsideParentOfNamespaceDeclarations(bool useSymbolAnnotations) { await TestAsync( @"namespace N { class C { } } namespace N.N1 { class C1 { private N.C c; } }", @"namespace N { class C { } } namespace N.N1 { class C1 { private N.C c; } }", @"namespace N { class C { } } namespace N.N1 { class C1 { private C c; } }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] public async Task TestImportNotAddedForReferencesMatchingNestedImports(bool useSymbolAnnotations) { await TestAsync( @"namespace N { using System.Collections.Generic; class C { private System.Collections.Generic.List<int> F; } }", @"namespace N { using System.Collections.Generic; class C { private System.Collections.Generic.List<int> F; } }", @"namespace N { using System.Collections.Generic; class C { private List<int> F; } }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] public async Task TestImportRemovedIfItMakesReferenceAmbiguous(bool useSymbolAnnotations) { // this is not really an artifact of the AddImports feature, it is due // to Simplifier not reducing the namespace reference because it would // become ambiguous, thus leaving an unused using directive await TestAsync( @"namespace N { class C { } } class C { public N.C F; }", @"using N; namespace N { class C { } } class C { public N.C F; }", @"namespace N { class C { } } class C { public N.C F; }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] [WorkItem(8797, "https://github.com/dotnet/roslyn/issues/8797")] public async Task TestBannerTextRemainsAtTopOfDocumentWithoutExistingImports(bool useSymbolAnnotations) { await TestAsync( @"// -------------------------------------------------------------------------------------------------------------------- // <copyright file=""File.cs"" company=""MyOrgnaization""> // Copyright (C) MyOrgnaization 2016 // </copyright> // -------------------------------------------------------------------------------------------------------------------- class C { public System.Collections.Generic.List<int> F; }", @"// -------------------------------------------------------------------------------------------------------------------- // <copyright file=""File.cs"" company=""MyOrgnaization""> // Copyright (C) MyOrgnaization 2016 // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System.Collections.Generic; class C { public System.Collections.Generic.List<int> F; }", @"// -------------------------------------------------------------------------------------------------------------------- // <copyright file=""File.cs"" company=""MyOrgnaization""> // Copyright (C) MyOrgnaization 2016 // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System.Collections.Generic; class C { public List<int> F; }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] [WorkItem(8797, "https://github.com/dotnet/roslyn/issues/8797")] public async Task TestBannerTextRemainsAtTopOfDocumentWithExistingImports(bool useSymbolAnnotations) { await TestAsync( @"// -------------------------------------------------------------------------------------------------------------------- // <copyright file=""File.cs"" company=""MyOrgnaization""> // Copyright (C) MyOrgnaization 2016 // </copyright> // -------------------------------------------------------------------------------------------------------------------- using ZZZ; class C { public System.Collections.Generic.List<int> F; }", @"// -------------------------------------------------------------------------------------------------------------------- // <copyright file=""File.cs"" company=""MyOrgnaization""> // Copyright (C) MyOrgnaization 2016 // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System.Collections.Generic; using ZZZ; class C { public System.Collections.Generic.List<int> F; }", @"// -------------------------------------------------------------------------------------------------------------------- // <copyright file=""File.cs"" company=""MyOrgnaization""> // Copyright (C) MyOrgnaization 2016 // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System.Collections.Generic; using ZZZ; class C { public List<int> F; }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] [WorkItem(8797, "https://github.com/dotnet/roslyn/issues/8797")] public async Task TestLeadingWhitespaceLinesArePreserved(bool useSymbolAnnotations) { await TestAsync( @"class C { public System.Collections.Generic.List<int> F; }", @"using System.Collections.Generic; class C { public System.Collections.Generic.List<int> F; }", @"using System.Collections.Generic; class C { public List<int> F; }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] public async Task TestImportAddedToNestedImports(bool useSymbolAnnotations) { await TestAsync( @"namespace N { using System; class C { private System.Collections.Generic.List<int> F; } }", @"namespace N { using System; using System.Collections.Generic; class C { private System.Collections.Generic.List<int> F; } }", @"namespace N { using System; using System.Collections.Generic; class C { private List<int> F; } }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] public async Task TestImportNameNotSimplfied(bool useSymbolAnnotations) { await TestAsync( @"namespace System { using System.Threading; class C { private System.Collections.Generic.List<int> F; } }", @"namespace System { using System.Collections.Generic; using System.Threading; class C { private System.Collections.Generic.List<int> F; } }", @"namespace System { using System.Collections.Generic; using System.Threading; class C { private List<int> F; } }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] public async Task TestUnnecessaryImportAddedAndRemoved(bool useSymbolAnnotations) { await TestAsync( @"using List = System.Collections.Generic.List<int>; namespace System { class C { private List F; } }", @"using System.Collections.Generic; using List = System.Collections.Generic.List<int>; namespace System { class C { private List F; } }", @"using List = System.Collections.Generic.List<int>; namespace System { class C { private List F; } }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] public async Task TestImportAddedToStartOfDocumentIfNoNestedImports(bool useSymbolAnnotations) { await TestAsync( @"namespace N { class C { private System.Collections.Generic.List<int> F; } }", @"using System.Collections.Generic; namespace N { class C { private System.Collections.Generic.List<int> F; } }", @"using System.Collections.Generic; namespace N { class C { private List<int> F; } }", useSymbolAnnotations); } [Theory, MemberData(nameof(TestAllData))] [WorkItem(9228, "https://github.com/dotnet/roslyn/issues/9228")] public async Task TestDoNotAddDuplicateImportIfNamespaceIsDefinedInSourceAndExternalAssembly(bool useSymbolAnnotations) { var externalCode = @"namespace N.M { public class A : System.Attribute { } }"; var code = @"using System; using N.M; class C { public void M1(String p1) { } public void M2([A] String p2) { } }"; var otherAssemblyReference = GetInMemoryAssemblyReferenceForCode(externalCode); var ws = new AdhocWorkspace(); var emptyProject = ws.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Default, "test", "test.dll", LanguageNames.CSharp, metadataReferences: new[] { TestMetadata.Net451.mscorlib })); var project = emptyProject .AddMetadataReferences(new[] { otherAssemblyReference }) .WithCompilationOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); project = project.AddDocument("duplicate.cs", externalCode).Project; var document = project.AddDocument("test.cs", code); var options = document.Project.Solution.Workspace.Options; var compilation = await document.Project.GetCompilationAsync(CancellationToken.None); var compilerDiagnostics = compilation.GetDiagnostics(CancellationToken.None); Assert.Empty(compilerDiagnostics.Where(d => d.Severity == DiagnosticSeverity.Error)); var attribute = compilation.GetTypeByMetadataName("N.M.A"); var syntaxRoot = await document.GetSyntaxRootAsync(CancellationToken.None).ConfigureAwait(false); SyntaxNode p1SyntaxNode = syntaxRoot.DescendantNodes().OfType<ParameterSyntax>().FirstOrDefault(); // Add N.M.A attribute to p1. var editor = await DocumentEditor.CreateAsync(document, CancellationToken.None).ConfigureAwait(false); var attributeSyntax = editor.Generator.Attribute(editor.Generator.TypeExpression(attribute)); editor.AddAttribute(p1SyntaxNode, attributeSyntax); var documentWithAttribute = editor.GetChangedDocument(); // Add namespace import. var imported = useSymbolAnnotations ? await ImportAdder.AddImportsFromSymbolAnnotationAsync(documentWithAttribute, null, CancellationToken.None).ConfigureAwait(false) : await ImportAdder.AddImportsFromSyntaxesAsync(documentWithAttribute, null, CancellationToken.None).ConfigureAwait(false); var formatted = await Formatter.FormatAsync(imported, options); var actualText = (await formatted.GetTextAsync()).ToString(); Assert.Equal(@"using System; using N.M; class C { public void M1([global::N.M.A] String p1) { } public void M2([A] String p2) { } }", actualText); } private static MetadataReference GetInMemoryAssemblyReferenceForCode(string code) { var tree = CSharpSyntaxTree.ParseText(code); var compilation = CSharpCompilation .Create("test.dll", new[] { tree }) .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) .AddReferences(TestMetadata.Net451.mscorlib); return compilation.ToMetadataReference(); } #region AddImports Safe Tests [Fact] public async Task TestSafeWithMatchingSimpleName() { await TestNoImportsAddedAsync( @"using B; namespace A { class C1 {} class C2 {} } namespace B { class C1 {} } class C { C1 M(A.C2 c2) => default; }", useSymbolAnnotations: true); } [Fact] public async Task TestSafeWithMatchingGenericName() { await TestNoImportsAddedAsync( @"using B; namespace A { class C1<T> {} class C2 {} } namespace B { class C1<T> {} } class C { C1<int> M(A.C2 c2) => default; }", useSymbolAnnotations: true); } [Fact] public async Task TestSafeWithMatchingQualifiedName() { await TestNoImportsAddedAsync( @"using B; namespace A { class O {} class C2 {} } namespace B { class O { public class C1 {} } } class C { O.C1 M(A.C2 c2) => default; }", useSymbolAnnotations: true); } [Fact] public async Task TestSafeWithMatchingAliasedIdentifierName() { await TestNoImportsAddedAsync( @"using C1 = B.C1; namespace A { class C1 {} class C2 {} } namespace B { class C1 {} } namespace Inner { class C { C1 M(A.C2 c2) => default; } }", useSymbolAnnotations: true); } [Fact] public async Task TestSafeWithMatchingGenericNameAndTypeArguments() { await TestNoImportsAddedAsync( @"using B; namespace A { class C1<T> {} class C2 {} class C3 {} } namespace B { class C1<T> {} class C3 {} } class C { C1<C3> M(A.C2 c2) => default; }", useSymbolAnnotations: true); } [Fact] public async Task TestSafeWithMatchingGenericNameAndTypeArguments_DifferentArity() { await TestAsync( @"using B; namespace A { class C1<T, X> {} class C2 {} } namespace B { class C1<T> {} class C3 {} } class C { C1<C3> M(A.C2 c2) => default; }", @"using A; using B; namespace A { class C1<T, X> {} class C2 {} } namespace B { class C1<T> {} class C3 {} } class C { C1<C3> M(A.C2 c2) => default; }", @"using A; using B; namespace A { class C1<T, X> {} class C2 {} } namespace B { class C1<T> {} class C3 {} } class C { C1<C3> M(C2 c2) => default; }", useSymbolAnnotations: true); } [Fact] public async Task TestSafeWithMatchingQualifiedNameAndTypeArguments() { await TestNoImportsAddedAsync( @"using B; namespace A { class O {} class C2 {} class C3 {} } namespace B { class C3 {} class O { public class C1<T> {} } } class C { O.C1<C3> M(A.C2 c2) => default; }", useSymbolAnnotations: true); } [Fact, WorkItem(39641, "https://github.com/dotnet/roslyn/issues/39641")] public async Task TestSafeWithMatchingSimpleNameInAllLocations() { await TestNoImportsAddedAsync( @"using B; using System.Collections.Generic; namespace A { class C1 { } class C2 { } } namespace B { class C1 { public static C1 P { get; } } } #nullable enable #pragma warning disable class C { /// <summary> /// <see cref=""C1""/> /// </summary> C1 M(C1 c1, A.C2 c2) { C1 result = (C1)c1 ?? new C1() ?? C1.P ?? new C1[0] { }[0] ?? new List<C1>()[0] ?? (C1?)null; (C1 a, int b) = (default, default); return result; } }", useSymbolAnnotations: true); } [Fact] public async Task TestSafeWithMatchingExtensionMethod() { await TestNoImportsAddedAsync( @"using B; namespace A { static class AExtensions { public static void M(this int a){} } public class C1 {} } namespace B { static class BExtensions { public static void M(this int a){} } } class C { void M(A.C1 c1) => 42.M(); }", useSymbolAnnotations: true); } [Fact] public async Task TestSafeWithMatchingExtensionMethodAndArguments() { await TestNoImportsAddedAsync( @"using B; namespace A { static class AExtensions { public static void M(this int a, C2 c2){} } public class C1 {} public class C2 {} } namespace B { static class BExtensions { public static void M(this int a, C2 c2){} } public class C2 {} } class C { void M(A.C1 c1) => 42.M(default(C2)); }", useSymbolAnnotations: true); } [Fact] public async Task TestSafeWithMatchingExtensionMethodAndTypeArguments() { await TestNoImportsAddedAsync( @"using B; namespace A { static class AExtensions { public static void M<T>(this int a){} } public class C1 {} public class C2 {} } namespace B { static class BExtensions { public static void M<T>(this int a){} } public class C2 {} } class C { void M(A.C1 c1) => 42.M<C2>(); }", useSymbolAnnotations: true); } [Fact] public async Task TestSafeWithLambdaExtensionMethodAmbiguity() { await TestNoImportsAddedAsync( @"using System; class C { // Don't add a using for N even though it is used here. public N.Other x; public static void Main() { M(x => x.M1()); } public static void M(Action<C> a){} public static void M(Action<int> a){} public void M1(){} } namespace N { public class Other { } public static class Extensions { public static void M1(this int a){} } }", useSymbolAnnotations: true); } #endregion } }
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/xlf/CSharpWorkspaceExtensionsResources.it.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="it" original="../CSharpWorkspaceExtensionsResources.resx"> <body> <trans-unit id="EmptyResource"> <source>Remove this value when another is added.</source> <target state="translated">Rimuovere questo valore quando ne viene aggiunto un altro.</target> <note>https://github.com/Microsoft/msbuild/issues/1661</note> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="it" original="../CSharpWorkspaceExtensionsResources.resx"> <body> <trans-unit id="EmptyResource"> <source>Remove this value when another is added.</source> <target state="translated">Rimuovere questo valore quando ne viene aggiunto un altro.</target> <note>https://github.com/Microsoft/msbuild/issues/1661</note> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/ExtractMethod/Extensions.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 System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractMethod { internal static class Extensions { public static bool Succeeded(this OperationStatus status) => status.Flag.Succeeded(); public static bool FailedWithNoBestEffortSuggestion(this OperationStatus status) => status.Flag.Failed() && !status.Flag.HasBestEffort(); public static bool Failed(this OperationStatus status) => status.Flag.Failed(); public static bool Succeeded(this OperationStatusFlag flag) => (flag & OperationStatusFlag.Succeeded) != 0; public static bool Failed(this OperationStatusFlag flag) => !flag.Succeeded(); public static bool HasBestEffort(this OperationStatusFlag flag) => (flag & OperationStatusFlag.BestEffort) != 0; public static bool HasSuggestion(this OperationStatusFlag flag) => (flag & OperationStatusFlag.Suggestion) != 0; public static bool HasMask(this OperationStatusFlag flag, OperationStatusFlag mask) => (flag & mask) != 0x0; public static OperationStatusFlag RemoveFlag(this OperationStatusFlag baseFlag, OperationStatusFlag flagToRemove) => baseFlag & ~flagToRemove; public static ITypeSymbol? GetLambdaOrAnonymousMethodReturnType(this SemanticModel binding, SyntaxNode node) { var info = binding.GetSymbolInfo(node); if (info.Symbol == null) { return null; } var methodSymbol = info.Symbol as IMethodSymbol; if (methodSymbol?.MethodKind != MethodKind.AnonymousFunction) { return null; } return methodSymbol.ReturnType; } public static Task<SemanticDocument> WithSyntaxRootAsync(this SemanticDocument semanticDocument, SyntaxNode root, CancellationToken cancellationToken) => SemanticDocument.CreateAsync(semanticDocument.Document.WithSyntaxRoot(root), cancellationToken); /// <summary> /// get tokens with given annotation in current document /// </summary> public static SyntaxToken GetTokenWithAnnotation(this SemanticDocument document, SyntaxAnnotation annotation) => document.Root.GetAnnotatedNodesAndTokens(annotation).Single().AsToken(); /// <summary> /// resolve the given symbol against compilation this snapshot has /// </summary> public static T ResolveType<T>(this SemanticModel semanticModel, T symbol) where T : class, ITypeSymbol { // Can be cleaned up when https://github.com/dotnet/roslyn/issues/38061 is resolved var typeSymbol = (T?)symbol.GetSymbolKey().Resolve(semanticModel.Compilation).GetAnySymbol(); Contract.ThrowIfNull(typeSymbol); return (T)typeSymbol.WithNullableAnnotation(symbol.NullableAnnotation); } /// <summary> /// check whether node contains error for itself but not from its child node /// </summary> public static bool HasDiagnostics(this SyntaxNode node) { var set = new HashSet<Diagnostic>(node.GetDiagnostics()); foreach (var child in node.ChildNodes()) { set.ExceptWith(child.GetDiagnostics()); } return set.Count > 0; } public static bool FromScript(this SyntaxNode node) { if (node.SyntaxTree == null) { return false; } return node.SyntaxTree.Options.Kind != SourceCodeKind.Regular; } } }
// Licensed to the .NET Foundation under one or more 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 System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractMethod { internal static class Extensions { public static bool Succeeded(this OperationStatus status) => status.Flag.Succeeded(); public static bool FailedWithNoBestEffortSuggestion(this OperationStatus status) => status.Flag.Failed() && !status.Flag.HasBestEffort(); public static bool Failed(this OperationStatus status) => status.Flag.Failed(); public static bool Succeeded(this OperationStatusFlag flag) => (flag & OperationStatusFlag.Succeeded) != 0; public static bool Failed(this OperationStatusFlag flag) => !flag.Succeeded(); public static bool HasBestEffort(this OperationStatusFlag flag) => (flag & OperationStatusFlag.BestEffort) != 0; public static bool HasSuggestion(this OperationStatusFlag flag) => (flag & OperationStatusFlag.Suggestion) != 0; public static bool HasMask(this OperationStatusFlag flag, OperationStatusFlag mask) => (flag & mask) != 0x0; public static OperationStatusFlag RemoveFlag(this OperationStatusFlag baseFlag, OperationStatusFlag flagToRemove) => baseFlag & ~flagToRemove; public static ITypeSymbol? GetLambdaOrAnonymousMethodReturnType(this SemanticModel binding, SyntaxNode node) { var info = binding.GetSymbolInfo(node); if (info.Symbol == null) { return null; } var methodSymbol = info.Symbol as IMethodSymbol; if (methodSymbol?.MethodKind != MethodKind.AnonymousFunction) { return null; } return methodSymbol.ReturnType; } public static Task<SemanticDocument> WithSyntaxRootAsync(this SemanticDocument semanticDocument, SyntaxNode root, CancellationToken cancellationToken) => SemanticDocument.CreateAsync(semanticDocument.Document.WithSyntaxRoot(root), cancellationToken); /// <summary> /// get tokens with given annotation in current document /// </summary> public static SyntaxToken GetTokenWithAnnotation(this SemanticDocument document, SyntaxAnnotation annotation) => document.Root.GetAnnotatedNodesAndTokens(annotation).Single().AsToken(); /// <summary> /// resolve the given symbol against compilation this snapshot has /// </summary> public static T ResolveType<T>(this SemanticModel semanticModel, T symbol) where T : class, ITypeSymbol { // Can be cleaned up when https://github.com/dotnet/roslyn/issues/38061 is resolved var typeSymbol = (T?)symbol.GetSymbolKey().Resolve(semanticModel.Compilation).GetAnySymbol(); Contract.ThrowIfNull(typeSymbol); return (T)typeSymbol.WithNullableAnnotation(symbol.NullableAnnotation); } /// <summary> /// check whether node contains error for itself but not from its child node /// </summary> public static bool HasDiagnostics(this SyntaxNode node) { var set = new HashSet<Diagnostic>(node.GetDiagnostics()); foreach (var child in node.ChildNodes()) { set.ExceptWith(child.GetDiagnostics()); } return set.Count > 0; } public static bool FromScript(this SyntaxNode node) { if (node.SyntaxTree == null) { return false; } return node.SyntaxTree.Options.Kind != SourceCodeKind.Regular; } } }
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/CSharp/Impl/xlf/VSPackage.fr.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="fr" original="../VSPackage.resx"> <body> <trans-unit id="101"> <source>C#</source> <target state="translated">C#</target> <note>Used many places.</note> </trans-unit> <trans-unit id="102"> <source>Advanced</source> <target state="translated">Avancé</target> <note>"Advanced" node under Tools &gt; Options, Text Editor, C#.</note> </trans-unit> <trans-unit id="103"> <source>IntelliSense</source> <target state="translated">IntelliSense</target> <note>"IntelliSense" node under Tools &gt; Options, Text Editor, C#.</note> </trans-unit> <trans-unit id="104"> <source>C# Editor</source> <target state="translated">C# - Éditeur</target> <note>"C# Editor" node in profile Import/Export.</note> </trans-unit> <trans-unit id="105"> <source>Settings for the C# editor found under the Advanced, Formatting, and IntelliSense nodes in the Tools/Options dialog box.</source> <target state="translated">Paramètres de l'Éditeur C# accessibles à partir des noeuds Avancé, Mise en forme et IntelliSense via la boîte de dialogue Outils/Options.</target> <note>"C# Editor" node help text in profile Import/Export.</note> </trans-unit> <trans-unit id="106"> <source>Settings for general C# options found under the General and Tabs nodes in the Tools/Options dialog box.</source> <target state="translated">Paramètres des options C# générales accessibles à partir des noeuds Général et Tabulations via la boîte de dialogue Outils/Options.</target> <note>"C#" node help text in profile Import/Export.</note> </trans-unit> <trans-unit id="306"> <source>Underline reassigned variables; Display inline hints; Show diagnostics for closed files; Colorize regular expression; Highlight related components under cursor; Report invalid regular expressions; Enable full solution analysis; Perform editor feature analysis in external process; Enable navigation to decompiled sources; Using directives; Place system directives first when sorting usings; Separate using directive groups; Suggest usings for types in reference assemblies; Suggest usings for types in NuGet packages; Highlighting; Highlight references to symbol under cursor; Highlight related keywords under cursor; Outlining; Enter outlining mode when files open; Show procedure line separators; Show outlining for declaration level constructs; Show outlining for code level constructs; Show outlining for comments and preprocessor regions; Collapse regions when collapsing to definitions; Fading; Fade out unused usings; Fade out unreachable code; Block Structure Guides; Show guides for declaration level constructs; Show guides for code level constructs; Editor Help; Generate XML documentation comments for ///; Insert * at the start of new lines when writing /* */ comments; Show preview for rename tracking; Split string literals on Enter; Report invalid placeholders in string.Format calls; Extract Method; Don't put ref or out on custom struct; Implement Interface or Abstract Class; When inserting properties, events and methods, place them; with other members of the same kind; at the end; When generating property; prefer throwing properties; prefer auto properties; regex; regular expression; Use enhanced colors; Editor Color Scheme; Inheritance Margin;</source> <target state="needs-review-translation">Afficher les indicateurs inline ; Afficher les diagnostics pour les fichiers fermés ; Mettre en couleurs l'expression régulière ; Surligner les composants liés sous le curseur ; Signaler les expressions régulières non valides ; Activer l'analyse complète de la solution ; Effectuer l'analyse des fonctionnalités de l'éditeur dans un processus externe ; Activer la navigation vers les sources décompilées ; Directives using ; Placer en premier les directives system au moment du tri des using ; Séparer les groupes de directives using ; Suggérer des using pour les types dans les assemblys de référence ; Suggérer des using pour les types dans les packages NuGet ; Mise en surbrillance ; Mettre en surbrillance les références au symbole sous le curseur ; Mettre en surbrillance les mots clés liés sous le curseur ; Mode Plan ; Passer en mode Plan à l'ouverture des fichiers ; Afficher les séparateurs de ligne de procédure ; Afficher le mode Plan pour les constructions au niveau des déclarations ; Afficher le mode Plan pour les constructions au niveau du code ; Afficher le mode Plan pour les commentaires et les régions du préprocesseur ; Réduire les régions au moment de la réduction aux définitions ; Atténuation ; Atténuer les using inutilisés ; Atténuer le code inaccessible ; Repères de structure de bloc ; Afficher les repères pour les constructions au niveau des déclarations ; Afficher les repères pour les constructions au niveau du code ; Aide de l'éditeur ; Générer des commentaires de documentation XML pour /// ; Insérer * au début des nouvelles lignes pour l'écriture de commentaires /* */ ; Afficher un aperçu pour le suivi des renommages ; Diviser les littéraux de chaîne avec Entrée ; Signaler les espaces réservés non valides dans les appels de string.Format ; Extraire la méthode ; Ne pas placer ref ou out dans un struct personnalisé ; Implémenter une interface ou une classe abstraite ; Au moment d'insérer des propriétés, des événements et des méthodes, les placer ; avec d'autres membres du même genre ; à la fin ; Durant la génération de propriétés ; préférer les propriétés de levée d'exceptions ; préférer les propriétés automatiques ; regex ; expression régulière ; Utiliser des couleurs améliorées ; Modèle de couleurs de l'éditeur ;</target> <note>C# Advanced options page keywords</note> </trans-unit> <trans-unit id="307"> <source>Automatically format when typing; Automatically format statement on semicolon ; Automatically format block on end brace; Automatically format on return; Automatically format on paste;</source> <target state="translated">Mettre en forme automatiquement en cours de frappe ; Mettre en forme automatiquement l'instruction quand un point-virgule est entré ; Mettre en forme automatiquement le bloc quand une accolade de fin est entrée ; Mettre en forme automatiquement au retour ; Mettre en forme automatiquement au moment du collage ;</target> <note>C# Formatting &gt; General options page keywords</note> </trans-unit> <trans-unit id="308"> <source>Indent block contents; indent open and close braces; indent case contents; indent case contents (when block); indent case labels; label indentation; place goto labels in leftmost column; indent labels normally; place goto labels one indent less than current;</source> <target state="translated">Mettre en retrait le contenu d'un bloc ; mettre en retrait les accolades ouvrantes et fermantes ; mettre en retrait le contenu de case ; mettre en retrait le contenu de case (dans un bloc) ; mettre en retrait les étiquettes case ; mise en retrait d'étiquette ; placer des étiquettes goto dans la colonne située le plus à gauche ; mettre en retrait normalement les étiquettes ; placer les étiquettes goto en retrait d'un niveau par rapport au niveau actuel ;</target> <note>C# Formatting &gt; Indentation options page keywords</note> </trans-unit> <trans-unit id="309"> <source>New line formatting option for braces;New line formatting options for keywords;New line options for braces; Place open brace on new line for types; Place open brace on new line for methods and local functions; Place open brace on new line for properties, indexers, and events; Place open brace on new line for property, indexer, and event accessors; Place open brace on new line for anonymous methods; Place open brace on new line for control blocks; Place open brace on new line for anonymous types; Place open brace on new line for object, collection and array initializers; New line options for keywords; Place else on new line; Place catch on new line; Place finally on new line; New line options for expression; Place members in object initializers on new line; Place members in anonymous types on new line; Place query expression clauses on new line;</source> <target state="translated">Nouvelle option de mise en forme de ligne pour les accolades;Nouvelles options de mise en forme de ligne pour les mots clés;Nouvelles options de ligne pour les accolades; Placer une accolade ouvrante sur une nouvelle ligne pour les types ; Placer une accolade ouvrante sur une nouvelle ligne pour les méthodes et les fonctions locales ; Placer une accolade ouvrante sur une nouvelle ligne pour les propriétés, indexeurs et événements ; Placer une accolade ouvrante sur une nouvelle ligne pour les accesseurs de propriété, d'indexeur et d'événement ; Placer une accolade ouvrante sur une nouvelle ligne pour les méthodes anonymes ; Placer l'accolade ouvrante sur une nouvelle ligne pour les blocs de contrôle ; Placer une accolade ouvrante sur une nouvelle ligne pour les types anonymes ; Placer une accolade ouvrante sur une nouvelle ligne pour les initialiseurs d'objet, de collection et de tableau ; Nouvelles options de ligne pour les mots clés ; Placer else sur une nouvelle ligne ; Placer catch sur une nouvelle ligne ; Placer finally sur une nouvelle ligne ; Nouvelles options de lignes pour expressions ; Placer les membres dans les initialiseurs d'objets sur une nouvelle ligne ; Placer les membres dans les types anonymes sur une nouvelle ligne ; Placer les clauses d'expression de requête sur une nouvelle ligne ;</target> <note>C# Formatting &gt; New Lines options page keywords</note> </trans-unit> <trans-unit id="310"> <source>Set spacing for method declarations; Insert space between method name and its opening parenthesis; Insert space within parameter list parentheses; Insert space within empty parameter list parentheses; Set spacing for method calls; Insert space within argument list parentheses; Insert space within empty argument list parentheses; Set other spacing options; Insert space after keywords in control flow statements; Insert space within parentheses of expressions; Insert space within parentheses of type casts; Insert spaces within parentheses of control flow statements; Insert space after cast; Ignore spaces in declaration statements; Set spacing for brackets; Insert space before open square bracket; Insert space within empty square brackets; Insert spaces within square brackets; Set spacing for delimiters; Insert space after colon for base or interface in type declaration; Insert space after comma; Insert space after dot; Insert space after semicolon in for statement; Insert space before colon for base or interface in type declaration; Insert space before comma; Insert space before dot; Insert space before semicolon in for statement; Set spacing for operators; Ignore spaces around binary operators; Remove spaces before and after binary operators; Insert space before and after binary operators;</source> <target state="translated">Définir l'espacement des déclarations de méthode ; Insérer un espace entre le nom de la méthode et sa parenthèse ouvrante ; Insérer un espace dans les parenthèses de la liste de paramètres ; Insérer un espace dans les parenthèses de la liste de paramètres vide ; Définir l'espacement des appels de méthode ; Insérer un espace dans les parenthèses de la liste d'arguments ; Insérer un espace dans les parenthèses de la liste d'arguments vide ; Définir d'autres options d'espacement ; Insérer un espace après les mots clés dans les instructions de flux de contrôle ; Insérer un espace dans les parenthèses d'expressions ; Insérer un espace dans les parenthèses de casts de type ; Insérer des espaces à l'intérieur des parenthèses des instructions de flux de contrôle ; Insérer un espace après cast ; Ignorer les espaces dans les instructions de déclaration ; Définir l'espacement des crochets ; Insérer un espace avant un crochet ouvrant ; Insérer un espace dans des crochets vides ; Insérer des espaces dans des crochets ; Définir l'espacement des délimiteurs ; Insérer un espace après le signe deux-points pour base ou interface dans une déclaration de type ; Insérer un espace après la virgule ; Insérer un espace après le point ; Insérer un espace après le point-virgule dans une instruction for ; Insérer un espace avant le signe deux-points pour base ou interface dans une déclaration de type ; Insérer un espace avant la virgule ; Insérer un espace avant le point ; Insérer un espace avant le point-virgule dans une instruction for ; Définir l'espacement des opérateurs ; Ignorer les espaces autour des opérateurs binaires ; Supprimer les espaces avant et après les opérateurs binaires ; Insérer un espace avant et après les opérateurs binaires ;</target> <note>C# Formatting &gt; Spacing options page keywords</note> </trans-unit> <trans-unit id="311"> <source>Change formatting options for wrapping;leave block on single line;leave statements and member declarations on the same line</source> <target state="translated">Changer les options de mise en forme pour l'enveloppement ; Laisser un bloc sur une seule ligne ; Laisser les instructions et les déclarations de membre sur la même ligne</target> <note>C# Formatting &gt; Wrapping options page keywords</note> </trans-unit> <trans-unit id="312"> <source>Change completion list settings;Pre-select most recently used member; Completion Lists; Show completion list after a character is typed; Show completion list after a character is deleted; Automatically show completion list in argument lists (experimental); Highlight matching portions of completion list items; Show completion item filters; Automatically complete statement on semicolon; Snippets behavior; Never include snippets; Always include snippets; Include snippets when ?-Tab is typed after an identifier; Enter key behavior; Never add new line on enter; Only add new line on enter after end of fully typed word; Always add new line on enter; Show name suggestions; Show items from unimported namespaces (experimental);</source> <target state="translated">Changer les paramètres de la liste de complétion;Présélectionner le dernier membre utilisé récemment;Listes de complétion; Afficher la liste de complétion une fois qu'un caractère a été tapé ; Afficher la liste de complétion après la suppression d'un caractère ; Afficher automatiquement la liste de complétion dans les listes d'arguments (expérimental) ; Mettre en surbrillance les parties correspondantes des éléments de liste de complétion ; Afficher les filtres d'éléments de complétion ; Effectuer la complétion automatique de l'instruction après l'entrée d'un point-virgule ; Comportement des extraits ; Ne jamais inclure d'extraits ; Toujours inclure les extraits ; Inclure les extraits quand ?-Tab est tapé après un identificateur ; Comportement de la touche Entrée ; Ne jamais ajouter de nouvelle ligne après Entrée ; Ajouter uniquement une nouvelle ligne une fois que la touche Entrée a été enfoncée à la fin du mot complet tapé ; Toujours ajouter une nouvelle ligne après Entrée ; Afficher les suggestions de nom ; Afficher les éléments des espaces de noms qui ne sont pas importés (expérimental) ;</target> <note>C# IntelliSense options page keywords</note> </trans-unit> <trans-unit id="107"> <source>Formatting</source> <target state="translated">Mise en forme</target> <note>"Formatting" category node under Tools &gt; Options, Text Editor, C#, Code Style (no corresponding keywords)</note> </trans-unit> <trans-unit id="108"> <source>General</source> <target state="translated">Général</target> <note>"General" node under Tools &gt; Options, Text Editor, C# (used for Code Style and Formatting)</note> </trans-unit> <trans-unit id="109"> <source>Indentation</source> <target state="translated">Retrait</target> <note>"Indentation" node under Tools &gt; Options, Text Editor, C#, Formatting.</note> </trans-unit> <trans-unit id="110"> <source>Wrapping</source> <target state="translated">Enveloppement</target> <note /> </trans-unit> <trans-unit id="111"> <source>New Lines</source> <target state="translated">Nouvelles lignes</target> <note /> </trans-unit> <trans-unit id="112"> <source>Spacing</source> <target state="translated">Espacement</target> <note /> </trans-unit> <trans-unit id="2358"> <source>C# Editor</source> <target state="translated">C# - Éditeur</target> <note /> </trans-unit> <trans-unit id="2359"> <source>C# Editor with Encoding</source> <target state="translated">Éditeur C# avec encodage</target> <note /> </trans-unit> <trans-unit id="113"> <source>Microsoft Visual C#</source> <target state="translated">Microsoft Visual C#</target> <note>Used for String in Tools &gt; Options, Text Editor, File Extensions</note> </trans-unit> <trans-unit id="114"> <source>Code Style</source> <target state="translated">Style de code</target> <note>"Code Style" category node under Tools &gt; Options, Text Editor, C# (no corresponding keywords)</note> </trans-unit> <trans-unit id="313"> <source>Style;Qualify;This;Code Style;var;member access;locals;parameters;var preferences;predefined type;framework type;built-in types;when variable type is apparent;elsewhere;qualify field access;qualify property access; qualify method access;qualify event access;</source> <target state="translated">Style;Qualifier;This;Style de code;var;accès au membre;variables locales;paramètres;préférences de variable;type prédéfini;type d'infrastructure;types intégrés;quand le type de variable est apparent;ailleurs;qualifier l'accès aux champs;qualifier l'accès aux propriétés; qualifier l'accès aux méthodes;qualifier l'accès aux événements;</target> <note>C# Code Style options page keywords</note> </trans-unit> <trans-unit id="115"> <source>Naming</source> <target state="translated">Affectation de noms</target> <note /> </trans-unit> <trans-unit id="314"> <source>Naming Style;Name Styles;Naming Rule;Naming Conventions</source> <target state="translated">Style de nommage;Styles de nom;Règle de nommage;Conventions de nommage</target> <note>C# Naming Style options page keywords</note> </trans-unit> <trans-unit id="116"> <source>C# Tools</source> <target state="translated">Outils C#</target> <note>Help &gt; About</note> </trans-unit> <trans-unit id="117"> <source>C# components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.</source> <target state="translated">Composants C# utilisés dans l'IDE. Selon votre type de projet et vos paramètres, une version différente du compilateur peut être utilisée.</target> <note>Help &gt; About</note> </trans-unit> <trans-unit id="An_empty_CSharp_script_file"> <source>An empty C# script file.</source> <target state="translated">Fichier de script C# vide.</target> <note /> </trans-unit> <trans-unit id="Visual_CSharp_Script"> <source>Visual C# Script</source> <target state="translated">Script Visual C#</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="fr" original="../VSPackage.resx"> <body> <trans-unit id="101"> <source>C#</source> <target state="translated">C#</target> <note>Used many places.</note> </trans-unit> <trans-unit id="102"> <source>Advanced</source> <target state="translated">Avancé</target> <note>"Advanced" node under Tools &gt; Options, Text Editor, C#.</note> </trans-unit> <trans-unit id="103"> <source>IntelliSense</source> <target state="translated">IntelliSense</target> <note>"IntelliSense" node under Tools &gt; Options, Text Editor, C#.</note> </trans-unit> <trans-unit id="104"> <source>C# Editor</source> <target state="translated">C# - Éditeur</target> <note>"C# Editor" node in profile Import/Export.</note> </trans-unit> <trans-unit id="105"> <source>Settings for the C# editor found under the Advanced, Formatting, and IntelliSense nodes in the Tools/Options dialog box.</source> <target state="translated">Paramètres de l'Éditeur C# accessibles à partir des noeuds Avancé, Mise en forme et IntelliSense via la boîte de dialogue Outils/Options.</target> <note>"C# Editor" node help text in profile Import/Export.</note> </trans-unit> <trans-unit id="106"> <source>Settings for general C# options found under the General and Tabs nodes in the Tools/Options dialog box.</source> <target state="translated">Paramètres des options C# générales accessibles à partir des noeuds Général et Tabulations via la boîte de dialogue Outils/Options.</target> <note>"C#" node help text in profile Import/Export.</note> </trans-unit> <trans-unit id="306"> <source>Underline reassigned variables; Display inline hints; Show diagnostics for closed files; Colorize regular expression; Highlight related components under cursor; Report invalid regular expressions; Enable full solution analysis; Perform editor feature analysis in external process; Enable navigation to decompiled sources; Using directives; Place system directives first when sorting usings; Separate using directive groups; Suggest usings for types in reference assemblies; Suggest usings for types in NuGet packages; Highlighting; Highlight references to symbol under cursor; Highlight related keywords under cursor; Outlining; Enter outlining mode when files open; Show procedure line separators; Show outlining for declaration level constructs; Show outlining for code level constructs; Show outlining for comments and preprocessor regions; Collapse regions when collapsing to definitions; Fading; Fade out unused usings; Fade out unreachable code; Block Structure Guides; Show guides for declaration level constructs; Show guides for code level constructs; Editor Help; Generate XML documentation comments for ///; Insert * at the start of new lines when writing /* */ comments; Show preview for rename tracking; Split string literals on Enter; Report invalid placeholders in string.Format calls; Extract Method; Don't put ref or out on custom struct; Implement Interface or Abstract Class; When inserting properties, events and methods, place them; with other members of the same kind; at the end; When generating property; prefer throwing properties; prefer auto properties; regex; regular expression; Use enhanced colors; Editor Color Scheme; Inheritance Margin;</source> <target state="needs-review-translation">Afficher les indicateurs inline ; Afficher les diagnostics pour les fichiers fermés ; Mettre en couleurs l'expression régulière ; Surligner les composants liés sous le curseur ; Signaler les expressions régulières non valides ; Activer l'analyse complète de la solution ; Effectuer l'analyse des fonctionnalités de l'éditeur dans un processus externe ; Activer la navigation vers les sources décompilées ; Directives using ; Placer en premier les directives system au moment du tri des using ; Séparer les groupes de directives using ; Suggérer des using pour les types dans les assemblys de référence ; Suggérer des using pour les types dans les packages NuGet ; Mise en surbrillance ; Mettre en surbrillance les références au symbole sous le curseur ; Mettre en surbrillance les mots clés liés sous le curseur ; Mode Plan ; Passer en mode Plan à l'ouverture des fichiers ; Afficher les séparateurs de ligne de procédure ; Afficher le mode Plan pour les constructions au niveau des déclarations ; Afficher le mode Plan pour les constructions au niveau du code ; Afficher le mode Plan pour les commentaires et les régions du préprocesseur ; Réduire les régions au moment de la réduction aux définitions ; Atténuation ; Atténuer les using inutilisés ; Atténuer le code inaccessible ; Repères de structure de bloc ; Afficher les repères pour les constructions au niveau des déclarations ; Afficher les repères pour les constructions au niveau du code ; Aide de l'éditeur ; Générer des commentaires de documentation XML pour /// ; Insérer * au début des nouvelles lignes pour l'écriture de commentaires /* */ ; Afficher un aperçu pour le suivi des renommages ; Diviser les littéraux de chaîne avec Entrée ; Signaler les espaces réservés non valides dans les appels de string.Format ; Extraire la méthode ; Ne pas placer ref ou out dans un struct personnalisé ; Implémenter une interface ou une classe abstraite ; Au moment d'insérer des propriétés, des événements et des méthodes, les placer ; avec d'autres membres du même genre ; à la fin ; Durant la génération de propriétés ; préférer les propriétés de levée d'exceptions ; préférer les propriétés automatiques ; regex ; expression régulière ; Utiliser des couleurs améliorées ; Modèle de couleurs de l'éditeur ;</target> <note>C# Advanced options page keywords</note> </trans-unit> <trans-unit id="307"> <source>Automatically format when typing; Automatically format statement on semicolon ; Automatically format block on end brace; Automatically format on return; Automatically format on paste;</source> <target state="translated">Mettre en forme automatiquement en cours de frappe ; Mettre en forme automatiquement l'instruction quand un point-virgule est entré ; Mettre en forme automatiquement le bloc quand une accolade de fin est entrée ; Mettre en forme automatiquement au retour ; Mettre en forme automatiquement au moment du collage ;</target> <note>C# Formatting &gt; General options page keywords</note> </trans-unit> <trans-unit id="308"> <source>Indent block contents; indent open and close braces; indent case contents; indent case contents (when block); indent case labels; label indentation; place goto labels in leftmost column; indent labels normally; place goto labels one indent less than current;</source> <target state="translated">Mettre en retrait le contenu d'un bloc ; mettre en retrait les accolades ouvrantes et fermantes ; mettre en retrait le contenu de case ; mettre en retrait le contenu de case (dans un bloc) ; mettre en retrait les étiquettes case ; mise en retrait d'étiquette ; placer des étiquettes goto dans la colonne située le plus à gauche ; mettre en retrait normalement les étiquettes ; placer les étiquettes goto en retrait d'un niveau par rapport au niveau actuel ;</target> <note>C# Formatting &gt; Indentation options page keywords</note> </trans-unit> <trans-unit id="309"> <source>New line formatting option for braces;New line formatting options for keywords;New line options for braces; Place open brace on new line for types; Place open brace on new line for methods and local functions; Place open brace on new line for properties, indexers, and events; Place open brace on new line for property, indexer, and event accessors; Place open brace on new line for anonymous methods; Place open brace on new line for control blocks; Place open brace on new line for anonymous types; Place open brace on new line for object, collection and array initializers; New line options for keywords; Place else on new line; Place catch on new line; Place finally on new line; New line options for expression; Place members in object initializers on new line; Place members in anonymous types on new line; Place query expression clauses on new line;</source> <target state="translated">Nouvelle option de mise en forme de ligne pour les accolades;Nouvelles options de mise en forme de ligne pour les mots clés;Nouvelles options de ligne pour les accolades; Placer une accolade ouvrante sur une nouvelle ligne pour les types ; Placer une accolade ouvrante sur une nouvelle ligne pour les méthodes et les fonctions locales ; Placer une accolade ouvrante sur une nouvelle ligne pour les propriétés, indexeurs et événements ; Placer une accolade ouvrante sur une nouvelle ligne pour les accesseurs de propriété, d'indexeur et d'événement ; Placer une accolade ouvrante sur une nouvelle ligne pour les méthodes anonymes ; Placer l'accolade ouvrante sur une nouvelle ligne pour les blocs de contrôle ; Placer une accolade ouvrante sur une nouvelle ligne pour les types anonymes ; Placer une accolade ouvrante sur une nouvelle ligne pour les initialiseurs d'objet, de collection et de tableau ; Nouvelles options de ligne pour les mots clés ; Placer else sur une nouvelle ligne ; Placer catch sur une nouvelle ligne ; Placer finally sur une nouvelle ligne ; Nouvelles options de lignes pour expressions ; Placer les membres dans les initialiseurs d'objets sur une nouvelle ligne ; Placer les membres dans les types anonymes sur une nouvelle ligne ; Placer les clauses d'expression de requête sur une nouvelle ligne ;</target> <note>C# Formatting &gt; New Lines options page keywords</note> </trans-unit> <trans-unit id="310"> <source>Set spacing for method declarations; Insert space between method name and its opening parenthesis; Insert space within parameter list parentheses; Insert space within empty parameter list parentheses; Set spacing for method calls; Insert space within argument list parentheses; Insert space within empty argument list parentheses; Set other spacing options; Insert space after keywords in control flow statements; Insert space within parentheses of expressions; Insert space within parentheses of type casts; Insert spaces within parentheses of control flow statements; Insert space after cast; Ignore spaces in declaration statements; Set spacing for brackets; Insert space before open square bracket; Insert space within empty square brackets; Insert spaces within square brackets; Set spacing for delimiters; Insert space after colon for base or interface in type declaration; Insert space after comma; Insert space after dot; Insert space after semicolon in for statement; Insert space before colon for base or interface in type declaration; Insert space before comma; Insert space before dot; Insert space before semicolon in for statement; Set spacing for operators; Ignore spaces around binary operators; Remove spaces before and after binary operators; Insert space before and after binary operators;</source> <target state="translated">Définir l'espacement des déclarations de méthode ; Insérer un espace entre le nom de la méthode et sa parenthèse ouvrante ; Insérer un espace dans les parenthèses de la liste de paramètres ; Insérer un espace dans les parenthèses de la liste de paramètres vide ; Définir l'espacement des appels de méthode ; Insérer un espace dans les parenthèses de la liste d'arguments ; Insérer un espace dans les parenthèses de la liste d'arguments vide ; Définir d'autres options d'espacement ; Insérer un espace après les mots clés dans les instructions de flux de contrôle ; Insérer un espace dans les parenthèses d'expressions ; Insérer un espace dans les parenthèses de casts de type ; Insérer des espaces à l'intérieur des parenthèses des instructions de flux de contrôle ; Insérer un espace après cast ; Ignorer les espaces dans les instructions de déclaration ; Définir l'espacement des crochets ; Insérer un espace avant un crochet ouvrant ; Insérer un espace dans des crochets vides ; Insérer des espaces dans des crochets ; Définir l'espacement des délimiteurs ; Insérer un espace après le signe deux-points pour base ou interface dans une déclaration de type ; Insérer un espace après la virgule ; Insérer un espace après le point ; Insérer un espace après le point-virgule dans une instruction for ; Insérer un espace avant le signe deux-points pour base ou interface dans une déclaration de type ; Insérer un espace avant la virgule ; Insérer un espace avant le point ; Insérer un espace avant le point-virgule dans une instruction for ; Définir l'espacement des opérateurs ; Ignorer les espaces autour des opérateurs binaires ; Supprimer les espaces avant et après les opérateurs binaires ; Insérer un espace avant et après les opérateurs binaires ;</target> <note>C# Formatting &gt; Spacing options page keywords</note> </trans-unit> <trans-unit id="311"> <source>Change formatting options for wrapping;leave block on single line;leave statements and member declarations on the same line</source> <target state="translated">Changer les options de mise en forme pour l'enveloppement ; Laisser un bloc sur une seule ligne ; Laisser les instructions et les déclarations de membre sur la même ligne</target> <note>C# Formatting &gt; Wrapping options page keywords</note> </trans-unit> <trans-unit id="312"> <source>Change completion list settings;Pre-select most recently used member; Completion Lists; Show completion list after a character is typed; Show completion list after a character is deleted; Automatically show completion list in argument lists (experimental); Highlight matching portions of completion list items; Show completion item filters; Automatically complete statement on semicolon; Snippets behavior; Never include snippets; Always include snippets; Include snippets when ?-Tab is typed after an identifier; Enter key behavior; Never add new line on enter; Only add new line on enter after end of fully typed word; Always add new line on enter; Show name suggestions; Show items from unimported namespaces (experimental);</source> <target state="translated">Changer les paramètres de la liste de complétion;Présélectionner le dernier membre utilisé récemment;Listes de complétion; Afficher la liste de complétion une fois qu'un caractère a été tapé ; Afficher la liste de complétion après la suppression d'un caractère ; Afficher automatiquement la liste de complétion dans les listes d'arguments (expérimental) ; Mettre en surbrillance les parties correspondantes des éléments de liste de complétion ; Afficher les filtres d'éléments de complétion ; Effectuer la complétion automatique de l'instruction après l'entrée d'un point-virgule ; Comportement des extraits ; Ne jamais inclure d'extraits ; Toujours inclure les extraits ; Inclure les extraits quand ?-Tab est tapé après un identificateur ; Comportement de la touche Entrée ; Ne jamais ajouter de nouvelle ligne après Entrée ; Ajouter uniquement une nouvelle ligne une fois que la touche Entrée a été enfoncée à la fin du mot complet tapé ; Toujours ajouter une nouvelle ligne après Entrée ; Afficher les suggestions de nom ; Afficher les éléments des espaces de noms qui ne sont pas importés (expérimental) ;</target> <note>C# IntelliSense options page keywords</note> </trans-unit> <trans-unit id="107"> <source>Formatting</source> <target state="translated">Mise en forme</target> <note>"Formatting" category node under Tools &gt; Options, Text Editor, C#, Code Style (no corresponding keywords)</note> </trans-unit> <trans-unit id="108"> <source>General</source> <target state="translated">Général</target> <note>"General" node under Tools &gt; Options, Text Editor, C# (used for Code Style and Formatting)</note> </trans-unit> <trans-unit id="109"> <source>Indentation</source> <target state="translated">Retrait</target> <note>"Indentation" node under Tools &gt; Options, Text Editor, C#, Formatting.</note> </trans-unit> <trans-unit id="110"> <source>Wrapping</source> <target state="translated">Enveloppement</target> <note /> </trans-unit> <trans-unit id="111"> <source>New Lines</source> <target state="translated">Nouvelles lignes</target> <note /> </trans-unit> <trans-unit id="112"> <source>Spacing</source> <target state="translated">Espacement</target> <note /> </trans-unit> <trans-unit id="2358"> <source>C# Editor</source> <target state="translated">C# - Éditeur</target> <note /> </trans-unit> <trans-unit id="2359"> <source>C# Editor with Encoding</source> <target state="translated">Éditeur C# avec encodage</target> <note /> </trans-unit> <trans-unit id="113"> <source>Microsoft Visual C#</source> <target state="translated">Microsoft Visual C#</target> <note>Used for String in Tools &gt; Options, Text Editor, File Extensions</note> </trans-unit> <trans-unit id="114"> <source>Code Style</source> <target state="translated">Style de code</target> <note>"Code Style" category node under Tools &gt; Options, Text Editor, C# (no corresponding keywords)</note> </trans-unit> <trans-unit id="313"> <source>Style;Qualify;This;Code Style;var;member access;locals;parameters;var preferences;predefined type;framework type;built-in types;when variable type is apparent;elsewhere;qualify field access;qualify property access; qualify method access;qualify event access;</source> <target state="translated">Style;Qualifier;This;Style de code;var;accès au membre;variables locales;paramètres;préférences de variable;type prédéfini;type d'infrastructure;types intégrés;quand le type de variable est apparent;ailleurs;qualifier l'accès aux champs;qualifier l'accès aux propriétés; qualifier l'accès aux méthodes;qualifier l'accès aux événements;</target> <note>C# Code Style options page keywords</note> </trans-unit> <trans-unit id="115"> <source>Naming</source> <target state="translated">Affectation de noms</target> <note /> </trans-unit> <trans-unit id="314"> <source>Naming Style;Name Styles;Naming Rule;Naming Conventions</source> <target state="translated">Style de nommage;Styles de nom;Règle de nommage;Conventions de nommage</target> <note>C# Naming Style options page keywords</note> </trans-unit> <trans-unit id="116"> <source>C# Tools</source> <target state="translated">Outils C#</target> <note>Help &gt; About</note> </trans-unit> <trans-unit id="117"> <source>C# components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.</source> <target state="translated">Composants C# utilisés dans l'IDE. Selon votre type de projet et vos paramètres, une version différente du compilateur peut être utilisée.</target> <note>Help &gt; About</note> </trans-unit> <trans-unit id="An_empty_CSharp_script_file"> <source>An empty C# script file.</source> <target state="translated">Fichier de script C# vide.</target> <note /> </trans-unit> <trans-unit id="Visual_CSharp_Script"> <source>Visual C# Script</source> <target state="translated">Script Visual C#</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Scripting/VisualBasic/xlf/VBScriptingResources.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="../VBScriptingResources.resx"> <body> <trans-unit id="LogoLine1"> <source>Microsoft (R) Visual Basic Interactive Compiler version {0}</source> <target state="translated">Microsoft (R) Visual Basic Interactive 編譯器 {0} 版</target> <note /> </trans-unit> <trans-unit id="LogoLine2"> <source>Copyright (C) Microsoft Corporation. All rights reserved.</source> <target state="translated">Copyright (C) Microsoft Corporation. 著作權所有,並保留一切權利。</target> <note /> </trans-unit> <trans-unit id="InteractiveHelp"> <source>Usage: vbi [options] [script-file.vbx] [-- script-arguments] If script-file is specified executes the script, otherwise launches an interactive REPL (Read Eval Print Loop). Options: /help Display this usage message (Short form: /?) /version Display the version and exit /reference:&lt;alias&gt;=&lt;file&gt; Reference metadata from the specified assembly file using the given alias (Short form: /r) /reference:&lt;file list&gt; Reference metadata from the specified assembly files (Short form: /r) /referencePath:&lt;path list&gt; List of paths where to look for metadata references specified as unrooted paths. (Short form: /rp) /using:&lt;namespace&gt; Define global namespace using (Short form: /u) /define:&lt;name&gt;=&lt;value&gt;,... Declare global conditional compilation symbol(s) (Short form: /d) @&lt;file&gt; Read response file for more options </source> <target state="translated">使用方式: vbi [options] [script-file.vbx] [-- script-arguments] 若已指定 script-file 則執行指令碼,否則會啟動互動式 REPL (「讀取、求值、輸出」迴圈)。 選項: /help 顯示使用方式訊息 (簡短形式: /?) /version 顯示版本並結束 /reference:&lt;別名&gt;=&lt;檔案&gt; 使用指定別名參考指定組件檔的中繼資料 (簡短形式: /r) /reference:&lt;檔案清單&gt; 參考指定組件檔的中繼資料 (簡短形式: /r) /referencePath:&lt;路徑清單&gt; 要尋找指定為非根路徑之中繼資料參考的路徑清單。(簡短形式: /rp) /using:&lt;命名空間&gt; 定義全域命名空間 using (簡短形式: /u) /define:&lt;名稱&gt;=&lt;值&gt;,... 宣告全域條件式編譯符號 (簡短形式: /d) @&lt;檔案&gt; 讀取回應檔以取得更多選項 </target> <note /> </trans-unit> <trans-unit id="ExceptionEscapeWithoutQuote"> <source>Cannot escape non-printable characters in Visual Basic notation unless quotes are used.</source> <target state="translated">除非使用引號,否則無法逸出 Visual Basic 標記法中不可列印的字元。</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="../VBScriptingResources.resx"> <body> <trans-unit id="LogoLine1"> <source>Microsoft (R) Visual Basic Interactive Compiler version {0}</source> <target state="translated">Microsoft (R) Visual Basic Interactive 編譯器 {0} 版</target> <note /> </trans-unit> <trans-unit id="LogoLine2"> <source>Copyright (C) Microsoft Corporation. All rights reserved.</source> <target state="translated">Copyright (C) Microsoft Corporation. 著作權所有,並保留一切權利。</target> <note /> </trans-unit> <trans-unit id="InteractiveHelp"> <source>Usage: vbi [options] [script-file.vbx] [-- script-arguments] If script-file is specified executes the script, otherwise launches an interactive REPL (Read Eval Print Loop). Options: /help Display this usage message (Short form: /?) /version Display the version and exit /reference:&lt;alias&gt;=&lt;file&gt; Reference metadata from the specified assembly file using the given alias (Short form: /r) /reference:&lt;file list&gt; Reference metadata from the specified assembly files (Short form: /r) /referencePath:&lt;path list&gt; List of paths where to look for metadata references specified as unrooted paths. (Short form: /rp) /using:&lt;namespace&gt; Define global namespace using (Short form: /u) /define:&lt;name&gt;=&lt;value&gt;,... Declare global conditional compilation symbol(s) (Short form: /d) @&lt;file&gt; Read response file for more options </source> <target state="translated">使用方式: vbi [options] [script-file.vbx] [-- script-arguments] 若已指定 script-file 則執行指令碼,否則會啟動互動式 REPL (「讀取、求值、輸出」迴圈)。 選項: /help 顯示使用方式訊息 (簡短形式: /?) /version 顯示版本並結束 /reference:&lt;別名&gt;=&lt;檔案&gt; 使用指定別名參考指定組件檔的中繼資料 (簡短形式: /r) /reference:&lt;檔案清單&gt; 參考指定組件檔的中繼資料 (簡短形式: /r) /referencePath:&lt;路徑清單&gt; 要尋找指定為非根路徑之中繼資料參考的路徑清單。(簡短形式: /rp) /using:&lt;命名空間&gt; 定義全域命名空間 using (簡短形式: /u) /define:&lt;名稱&gt;=&lt;值&gt;,... 宣告全域條件式編譯符號 (簡短形式: /d) @&lt;檔案&gt; 讀取回應檔以取得更多選項 </target> <note /> </trans-unit> <trans-unit id="ExceptionEscapeWithoutQuote"> <source>Cannot escape non-printable characters in Visual Basic notation unless quotes are used.</source> <target state="translated">除非使用引號,否則無法逸出 Visual Basic 標記法中不可列印的字元。</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Test/Semantic/Semantics/PatternMatchingTests.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.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.Patterns)] public class PatternMatchingTests : PatternMatchingTestBase { [Fact] public void DemoModes() { var source = @" public class Vec { public static void Main() { object o = ""Pass""; int i1 = 0b001010; // binary literals int i2 = 23_554; // digit separators // local functions // Note: due to complexity and cost of parsing local functions we // don't try to parse if the feature isn't enabled int f() => 2; ref int i3 = ref i1; // ref locals string s = o is string k ? k : null; // pattern matching //let var i4 = 3; // let //int i5 = o match (case * : 7); // match //object q = (o is null) ? o : throw null; // throw expressions //if (q is Vec(3)) {} // recursive pattern } public int X => 4; public Vec(int x) {} } "; CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular6).VerifyDiagnostics( // (7,18): error CS8059: Feature 'binary literals' is not available in C# 6. Please use language version 7.0 or greater. // int i1 = 0b001010; // binary literals Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "").WithArguments("binary literals", "7.0").WithLocation(7, 18), // (8,18): error CS8059: Feature 'digit separators' is not available in C# 6. Please use language version 7.0 or greater. // int i2 = 23_554; // digit separators Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "").WithArguments("digit separators", "7.0").WithLocation(8, 18), // (12,13): error CS8059: Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater. // int f() => 2; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "f").WithArguments("local functions", "7.0").WithLocation(12, 13), // (13,9): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref int i3 = ref i1; // ref locals Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(13, 9), // (13,22): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref int i3 = ref i1; // ref locals Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(13, 22), // (14,20): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // string s = o is string k ? k : null; // pattern matching Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "o is string k").WithArguments("pattern matching", "7.0").WithLocation(14, 20), // (12,13): warning CS8321: The local function 'f' is declared but never used // int f() => 2; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(12, 13) ); // enables binary literals, digit separators, local functions, ref locals, pattern matching CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics( // (8,13): warning CS0219: The variable 'i2' is assigned but its value is never used // int i2 = 23_554; // digit separators Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i2").WithArguments("i2").WithLocation(8, 13), // (12,13): warning CS8321: The local function 'f' is declared but never used // int f() => 2; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(12, 13) ); } [Fact] public void SimplePatternTest() { var source = @"using System; public class X { public static void Main() { var s = nameof(Main); if (s is string t) Console.WriteLine(""1. {0}"", t); s = null; Console.WriteLine(""2. {0}"", s is string w ? w : nameof(X)); int? x = 12; {if (x is var y) Console.WriteLine(""3. {0}"", y);} {if (x is int y) Console.WriteLine(""4. {0}"", y);} x = null; {if (x is var y) Console.WriteLine(""5. {0}"", y);} {if (x is int y) Console.WriteLine(""6. {0}"", y);} Console.WriteLine(""7. {0}"", (x is bool is bool)); } }"; var expectedOutput = @"1. Main 2. X 3. 12 4. 12 5. 7. True"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // warning CS0184: The given expression is never of the provided ('bool') type // Console.WriteLine("7. {0}", (x is bool is bool)); Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "x is bool").WithArguments("bool"), // warning CS0183: The given expression is always of the provided ('bool') type // Console.WriteLine("7. {0}", (x is bool is bool)); Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "x is bool is bool").WithArguments("bool") ); var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void NullablePatternTest() { var source = @"using System; public class X { public static void Main() { T(null); T(1); } public static void T(object x) { if (x is Nullable<int> y) Console.WriteLine($""expression {x} is Nullable<int> y""); } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (11,18): error CS8116: It is not legal to use nullable type 'int?' in a pattern; use the underlying type 'int' instead. // if (x is Nullable<int> y) Console.WriteLine($"expression {x} is Nullable<int> y"); Diagnostic(ErrorCode.ERR_PatternNullableType, "Nullable<int>").WithArguments("int").WithLocation(11, 18) ); } [Fact] public void UnconstrainedPatternTest() { var source = @"using System; public class X { public static void Main() { Test<string>(1); Test<int>(""goo""); Test<int>(1); Test<int>(1.2); Test<double>(1.2); Test<int?>(1); Test<int?>(null); Test<string>(null); } public static void Test<T>(object x) { if (x is T y) Console.WriteLine($""expression {x} is {typeof(T).Name} {y}""); else Console.WriteLine($""expression {x} is not {typeof(T).Name}""); } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); using (new EnsureInvariantCulture()) { var expectedOutput = @"expression 1 is not String expression goo is not Int32 expression 1 is Int32 1 expression 1.2 is not Int32 expression 1.2 is Double 1.2 expression 1 is Nullable`1 1 expression is not Nullable`1 expression is not String"; var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } } [Fact, WorkItem(10932, "https://github.com/dotnet/roslyn/issues/10932")] public void PatternErrors() { var source = @"using System; using NullableInt = System.Nullable<int>; public class X { public static void Main() { var s = nameof(Main); byte b = 1; if (s is string t) { } else Console.WriteLine(t); if (null is dynamic t2) { } // null not allowed if (s is NullableInt x) { } // error: cannot use nullable type if (s is long l) { } // error: cannot convert string to long if (b is 1000) { } // error: cannot convert 1000 to byte } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (10,13): error CS8117: Invalid operand for pattern match; value required, but found '<null>'. // if (null is dynamic t2) { } // null not allowed Diagnostic(ErrorCode.ERR_BadPatternExpression, "null").WithArguments("<null>").WithLocation(10, 13), // (11,18): error CS8116: It is not legal to use nullable type 'int?' in a pattern; use the underlying type 'int' instead. // if (s is NullableInt x) { } // error: cannot use nullable type Diagnostic(ErrorCode.ERR_PatternNullableType, "NullableInt").WithArguments("int").WithLocation(11, 18), // (12,18): error CS8121: An expression of type 'string' cannot be handled by a pattern of type 'long'. // if (s is long l) { } // error: cannot convert string to long Diagnostic(ErrorCode.ERR_PatternWrongType, "long").WithArguments("string", "long").WithLocation(12, 18), // (13,18): error CS0031: Constant value '1000' cannot be converted to a 'byte' // if (b is 1000) { } // error: cannot convert 1000 to byte Diagnostic(ErrorCode.ERR_ConstOutOfRange, "1000").WithArguments("1000", "byte").WithLocation(13, 18), // (9,55): error CS0165: Use of unassigned local variable 't' // if (s is string t) { } else Console.WriteLine(t); Diagnostic(ErrorCode.ERR_UseDefViolation, "t").WithArguments("t").WithLocation(9, 55) ); } [Fact] public void PatternInCtorInitializer() { var source = @"using System; public class X { public static void Main() { new D(1); new D(10); new D(1.2); } } class D { public D(object o) : this(o is int x && x >= 5) {} public D(bool b) { Console.WriteLine(b); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var expectedOutput = @"False True False"; var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void PatternInCatchFilter() { var source = @"using System; public class X { public static void Main() { M(1); M(10); M(1.2); } private static void M(object o) { try { throw new Exception(); } catch (Exception) when (o is int x && x >= 5) { Console.WriteLine($""Yes for {o}""); } catch (Exception) { Console.WriteLine($""No for {o}""); } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); using (new EnsureInvariantCulture()) { var expectedOutput = @"No for 1 Yes for 10 No for 1.2"; var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } } [ConditionalFact(typeof(DesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28026")] public void PatternInFieldInitializer() { var source = @"using System; public class X { static object o1 = 1; static object o2 = 10; static object o3 = 1.2; static bool b1 = M(o1, (o1 is int x && x >= 5)), b2 = M(o2, (o2 is int x && x >= 5)), b3 = M(o3, (o3 is int x && x >= 5)); public static void Main() { } private static bool M(object o, bool result) { Console.WriteLine($""{result} for {o}""); return result; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); using (new EnsureInvariantCulture()) { var expectedOutput = @"False for 1 True for 10 False for 1.2"; var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } } [Fact] public void PatternInExpressionBodiedMethod() { var source = @"using System; public class X { static object o1 = 1; static object o2 = 10; static object o3 = 1.2; static bool B1() => M(o1, (o1 is int x && x >= 5)); static bool B2 => M(o2, (o2 is int x && x >= 5)); static bool B3 => M(o3, (o3 is int x && x >= 5)); public static void Main() { var r = B1() | B2 | B3; } private static bool M(object o, bool result) { Console.WriteLine($""{result} for {o}""); return result; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); using (new EnsureInvariantCulture()) { var expectedOutput = @"False for 1 True for 10 False for 1.2"; var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } } [Fact, WorkItem(8778, "https://github.com/dotnet/roslyn/issues/8778")] public void PatternInExpressionBodiedLocalFunction() { var source = @"using System; public class X { static object o1 = 1; static object o2 = 10; static object o3 = 1.2; public static void Main() { bool B1() => M(o1, (o1 is int x && x >= 5)); bool B2() => M(o2, (o2 is int x && x >= 5)); bool B3() => M(o3, (o3 is int x && x >= 5)); var r = B1() | B2() | B3(); } private static bool M(object o, bool result) { Console.WriteLine($""{result} for {o}""); return result; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); using (new EnsureInvariantCulture()) { var expectedOutput = @"False for 1 True for 10 False for 1.2"; var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } } [Fact, WorkItem(8778, "https://github.com/dotnet/roslyn/issues/8778")] public void PatternInExpressionBodiedLambda() { var source = @"using System; public class X { public static void Main() { object o1 = 1; object o2 = 10; object o3 = 1.2; Func<object, bool> B1 = o => M(o, (o is int x && x >= 5)); B1(o1); Func<bool> B2 = () => M(o2, (o2 is int x && x >= 5)); B2(); Func<bool> B3 = () => M(o3, (o3 is int x && x >= 5)); B3(); } private static bool M(object o, bool result) { Console.WriteLine($""{result} for {o}""); return result; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); using (new EnsureInvariantCulture()) { var expectedOutput = @"False for 1 True for 10 False for 1.2"; var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } } [Fact] public void PatternInBadPlaces() { var source = @"using System; [Obsolete("""" is string s ? s : """")] public class X { public static void Main() { } private static void M(string p = """" is object o ? o.ToString() : """") { } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (2,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Obsolete("" is string s ? s : "")] Diagnostic(ErrorCode.ERR_BadAttributeArgument, @""""" is string s ? s : """"").WithLocation(2, 11), // (8,38): error CS1736: Default parameter value for 'p' must be a compile-time constant // private static void M(string p = "" is object o ? o.ToString() : "") Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, @""""" is object o ? o.ToString() : """"").WithArguments("p").WithLocation(8, 38) ); } [Fact] public void PatternInSwitchAndForeach() { var source = @"using System; public class X { public static void Main() { object o1 = 1; object o2 = 10; object o3 = 1.2; object oa = new object[] { 1, 10, 1.2 }; foreach (var o in oa is object[] z ? z : new object[0]) { switch (o is int x && x >= 5) { case true: M(o, true); break; case false: M(o, false); break; default: throw null; } } } private static bool M(object o, bool result) { Console.WriteLine($""{result} for {o}""); return result; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); using (new EnsureInvariantCulture()) { var expectedOutput = @"False for 1 True for 10 False for 1.2"; var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } } [Fact] public void GeneralizedSwitchStatement() { Uri u = new Uri("http://www.microsoft.com"); var source = @"using System; public struct X { public static void Main() { var oa = new object[] { 1, 10, 20L, 1.2, ""goo"", true, null, new X(), new Exception(""boo"") }; foreach (var o in oa) { switch (o) { default: Console.WriteLine($""class {o.GetType().Name} {o}""); break; case 1: Console.WriteLine(""one""); break; case int i: Console.WriteLine($""int {i}""); break; case long i: Console.WriteLine($""long {i}""); break; case double d: Console.WriteLine($""double {d}""); break; case null: Console.WriteLine($""null""); break; case ValueType z: Console.WriteLine($""struct {z.GetType().Name} {z}""); break; } } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); using (new EnsureInvariantCulture()) { var expectedOutput = @"one int 10 long 20 double 1.2 class String goo struct Boolean True null struct X X class Exception System.Exception: boo "; var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } } [Fact] public void PatternVariableDefiniteAssignment() { var source = @"using System; public class X { public static void Main() { object o = new X(); if (o is X x1) Console.WriteLine(x1); // OK if (!(o is X x2)) Console.WriteLine(x2); // error if (o is X x3 || true) Console.WriteLine(x3); // error switch (o) { case X x4: default: Console.WriteLine(x4); // error break; } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (8,45): error CS0165: Use of unassigned local variable 'x2' // if (!(o is X x2)) Console.WriteLine(x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(8, 45), // (9,50): error CS0165: Use of unassigned local variable 'x3' // if (o is X x3 || true) Console.WriteLine(x3); Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(9, 50), // (14,35): error CS0165: Use of unassigned local variable 'x4' // Console.WriteLine(x4); // error Diagnostic(ErrorCode.ERR_UseDefViolation, "x4").WithArguments("x4").WithLocation(14, 35) ); } [Fact] public void PatternVariablesAreMutable() { var source = @" public class X { public static void Main() { if (12 is var x) { x = x + 1; x++; M1(ref x); M2(out x); } } public static void M1(ref int x) {} public static void M2(out int x) { x = 1; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); } [Fact] public void If_01() { var source = @" public class X { public static void Main() { Test(1); Test(2); } public static void Test(int val) { if (Dummy(val == 1, val is var x1, x1)) { System.Console.WriteLine(""true""); System.Console.WriteLine(x1); } else { System.Console.WriteLine(""false""); System.Console.WriteLine(x1); } System.Console.WriteLine(x1); } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 true 1 1 2 false 2 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(4, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void If_02() { var source = @" public class X { public static void Main() { bool f = true; if (f) if (Dummy(f, (f ? 1 : 2) is var x1, x1)) ; if (f) { if (Dummy(f, (f ? 3 : 4) is var x1, x1)) ; } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0]); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]); } [Fact] public void Lambda_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static bool Test1() { System.Func<bool> l = () => 1 is int x1 && Dummy(x1); return l(); } static bool Dummy(int x) { System.Console.WriteLine(x); return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 True"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28026")] public void Query_01() { var source = @" using System.Linq; public class X { public static void Main() { Test1(); } static void Test1() { var res = from x1 in new[] { 1 is var y1 && Print(y1) ? 1 : 0} from x2 in new[] { 2 is var y2 && Print(y2) ? 1 : 0} join x3 in new[] { 3 is var y3 && Print(y3) ? 1 : 0} on 4 is var y4 && Print(y4) ? 1 : 0 equals 5 is var y5 && Print(y5) ? 1 : 0 where 6 is var y6 && Print(y6) orderby 7 is var y7 && Print(y7), 8 is var y8 && Print(y8) group 9 is var y9 && Print(y9) by 10 is var y10 && Print(y10) into g let x11 = 11 is var y11 && Print(y11) select 12 is var y12 && Print(y12); res.ToArray(); } static bool Print(object x) { System.Console.WriteLine(x); return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: @"1 3 5 2 4 6 7 8 10 9 11 12 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); for (int i = 1; i < 13; i++) { var id = "y" + i; var yDecl = GetPatternDeclarations(tree, id).Single(); var yRef = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(name => name.Identifier.ValueText == id).Single(); VerifyModelForDeclarationOrVarSimplePattern(model, yDecl, yRef); } } [Fact] public void Query_02() { var source = @" using System.Linq; public class X { public static void Main() { Test1(); } static void Test1() { var res = from x1 in new[] { 1 is var y1 && Print(y1) ? 2 : 0} select Print(x1); res.ToArray(); } static bool Print(object x) { System.Console.WriteLine(x); return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yDecl = GetPatternDeclaration(tree, "y1"); var yRef = GetReferences(tree, "y1").Single(); VerifyModelForDeclarationOrVarSimplePattern(model, yDecl, yRef); } [Fact] public void ExpressionBodiedFunctions_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static bool Test1() => 1 is int x1 && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] public void ExpressionBodiedProperties_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); System.Console.WriteLine(new X()[0]); } static bool Test1 => 2 is int x1 && Dummy(x1); bool this[object x] => 1 is int x1 && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"2 True 1 True"); } [Fact] public void FieldInitializers_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); } static bool Test1 = 1 is int x1 && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 True"); CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (9,34): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater. // static bool Test1 = 1 is int x1 && Dummy(x1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(9, 34) ); } [Fact, WorkItem(10487, "https://github.com/dotnet/roslyn/issues/10487")] public void FieldInitializers_03() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); new X().M(); } void M() { System.Console.WriteLine(Test2); } static bool Test1 = 1 is int x1 && Dummy(() => x1); bool Test2 = 2 is int x1 && Dummy(() => x1); static bool Dummy(System.Func<int> x) { System.Console.WriteLine(x()); return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 True 2 True"); } [Fact] [WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")] public void FieldInitializers_04() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static System.Func<bool> Test1 = () => 1 is int x1 && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] public void PropertyInitializers_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); } static bool Test1 {get;} = 1 is int x1 && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 True"); CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (9,41): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater. // static bool Test1 {get;} = 1 is int x1 && Dummy(x1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(9, 41) ); } [Fact] [WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")] public void PropertyInitializers_02() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static System.Func<bool> Test1 {get;} = () => 1 is int x1 && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] public void ConstructorInitializers_01() { var source = @" public class X { public static void Main() { var x = new D(); } } class D : C { public D(object o) : base(2 is var x1 && Dummy(x1)) { System.Console.WriteLine(o); } public D() : this(1 is int x1 && Dummy(x1)) { } static bool Dummy(int x) { System.Console.WriteLine(x); return true; } } class C { public C(object b) { System.Console.WriteLine(b); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 2 True True"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0]); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]); Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(x1Decl[0])).Type.ToTestDisplayString()); CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (12,40): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater. // public D(object o) : base(2 is var x1 && Dummy(x1)) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(12, 40), // (17,32): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater. // public D() : this(1 is int x1 && Dummy(x1)) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(17, 32) ); } [Fact] [WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")] public void ConstructorInitializers_02() { var source = @" public class X { public static void Main() { var x = new D(); } } class D : C { public D(System.Func<bool> o) : base(() => 2 is int x1 && Dummy(x1)) { System.Console.WriteLine(o()); } public D() : this(() => 1 is int x1 && Dummy(x1)) { } static bool Dummy(int x) { System.Console.WriteLine(x); return true; } } class C { public C(System.Func<bool> b) { System.Console.WriteLine(b()); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"2 True 1 True"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0]); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]); } [Fact] public void Switch_01() { var source = @" public class X { public static void Main() { Test1(0); Test1(1); } static bool Dummy1(bool val, params object[] x) {return val;} static T Dummy2<T>(T val, params object[] x) {return val;} static void Test1(int val) { switch (Dummy2(val, ""Test1 {0}"" is var x1)) { case 0 when Dummy1(true, ""case 0"" is var y1): System.Console.WriteLine(x1, y1); break; case int z1: System.Console.WriteLine(x1, z1); break; } System.Console.WriteLine(x1); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"Test1 case 0 Test1 {0} Test1 1 Test1 {0}"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void Switch_02() { var source = @" public class X { public static void Main() { bool f = true; if (f) switch (Dummy(f, (f ? 1 : 2) is var x1, x1)) {} if (f) { switch (Dummy(f, (f ? 3 : 4) is var x1, x1)) {} } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0]); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]); } [Fact] public void Using_01() { var source = @" public class X { public static void Main() { using (System.IDisposable d1 = Dummy(new C(""a""), new C(""b"") is var x1), d2 = Dummy(new C(""c""), new C(""d"") is var x2)) { System.Console.WriteLine(d1); System.Console.WriteLine(x1); System.Console.WriteLine(d2); System.Console.WriteLine(x2); } using (Dummy(new C(""e""), new C(""f"") is var x1)) { System.Console.WriteLine(x1); } } static System.IDisposable Dummy(System.IDisposable x, params object[] y) {return x;} } class C : System.IDisposable { private readonly string _val; public C(string val) { _val = val; } public void Dispose() { System.Console.WriteLine(""Disposing {0}"", _val); } public override string ToString() { return _val; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"a b c d Disposing c Disposing a f Disposing e"); } [Fact] public void LocalDeclarationStmt_01() { var source = @" public class X { public static void Main() { object d1 = Dummy(new C(""a""), new C(""b"") is var x1, x1), d2 = Dummy(new C(""c""), new C(""d"") is var x2, x2); System.Console.WriteLine(d1); System.Console.WriteLine(d2); System.Console.WriteLine(x1); } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"b d a c b"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").ToArray(); var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void LocalDeclarationStmt_02() { var source = @" public class X { public static void Main() { if (true) { object d1 = Dummy(new C(""a""), new C(""b"") is var x1, x1); } } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"b"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").ToArray(); var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void DeconstructionDeclarationStmt_01() { var source = @" public class X { public static void Main() { (object d1, object d2) = (Dummy(new C(""a""), (new C(""b"") is var x1), x1), Dummy(new C(""c""), (new C(""d"") is var x2), x2)); System.Console.WriteLine(d1); System.Console.WriteLine(d2); System.Console.WriteLine(x1); } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b d a c b"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void DeconstructionDeclarationStmt_02() { var source = @" public class X { public static void Main() { if (true) { (object d1, object d2) = (Dummy(new C(""a""), (new C(""b"") is var x1), x1), x1); } } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").ToArray(); var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void DeconstructionDeclarationStmt_03() { var source = @" public class X { public static void Main() { var (d1, (d2, d3)) = (Dummy(new C(""a""), (new C(""b"") is var x1), x1), (Dummy(new C(""c""), (new C(""d"") is var x2), x2), Dummy(new C(""e""), (new C(""f"") is var x3), x3))); System.Console.WriteLine(d1); System.Console.WriteLine(d2); System.Console.WriteLine(d3); System.Console.WriteLine(x1); System.Console.WriteLine(x2); System.Console.WriteLine(x3); } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b d f a c e b d f"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").ToArray(); var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); var x2Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x2").ToArray(); var x2Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x2").ToArray(); Assert.Equal(1, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl[0], x2Ref); var x3Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x3").ToArray(); var x3Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x3").ToArray(); Assert.Equal(1, x3Decl.Length); Assert.Equal(2, x3Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl[0], x3Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void DeconstructionDeclarationStmt_04() { var source = @" public class X { public static void Main() { (var d1, (var d2, var d3)) = (Dummy(new C(""a""), (new C(""b"") is var x1), x1), (Dummy(new C(""c""), (new C(""d"") is var x2), x2), Dummy(new C(""e""), (new C(""f"") is var x3), x3))); System.Console.WriteLine(d1); System.Console.WriteLine(d2); System.Console.WriteLine(d3); System.Console.WriteLine(x1); System.Console.WriteLine(x2); System.Console.WriteLine(x3); } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b d f a c e b d f"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); var x2Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x2").ToArray(); var x2Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x2").ToArray(); Assert.Equal(1, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl[0], x2Ref); var x3Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x3").ToArray(); var x3Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x3").ToArray(); Assert.Equal(1, x3Decl.Length); Assert.Equal(2, x3Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl[0], x3Ref); } [Fact] public void While_01() { var source = @" public class X { public static void Main() { bool f = true; while (Dummy(f, (f ? 1 : 2) is var x1, x1)) { System.Console.WriteLine(x1); f = false; } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 1 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void While_02() { var source = @" public class X { public static void Main() { bool f = true; if (f) while (Dummy(f, (f ? 1 : 2) is var x1, x1)) break; if (f) { while (Dummy(f, (f ? 3 : 4) is var x1, x1)) break; } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0]); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]); } [Fact] public void While_03() { var source = @" public class X { public static void Main() { int f = 1; var l = new System.Collections.Generic.List<System.Action>(); while (Dummy(f < 3, f is var x1, x1)) { l.Add(() => System.Console.WriteLine(x1)); f++; } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2 3 -- 1 2 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void While_04() { var source = @" public class X { public static void Main() { int f = 1; var l = new System.Collections.Generic.List<System.Action>(); while (Dummy(f < 3, f is var x1, x1, l, () => System.Console.WriteLine(x1))) { f++; } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2 3 -- 1 2 3 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void While_05() { var source = @" public class X { public static void Main() { int f = 1; var l = new System.Collections.Generic.List<System.Action>(); while (Dummy(f < 3, f is var x1, x1, l, () => System.Console.WriteLine(x1))) { l.Add(() => System.Console.WriteLine(x1)); f++; } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2 3 -- 1 1 2 2 3 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void Do_01() { var source = @" public class X { public static void Main() { bool f; do { f = false; } while (Dummy(f, (f ? 1 : 2) is var x1, x1)); } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void Do_02() { var source = @" public class X { public static void Main() { bool f = true; if (f) do ; while (Dummy(f, (f ? 1 : 2) is var x1, x1) && false); if (f) { do ; while (Dummy(f, (f ? 3 : 4) is var x1, x1) && false); } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0]); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]); } [Fact] public void Do_03() { var source = @" public class X { public static void Main() { int f = 1; var l = new System.Collections.Generic.List<System.Action>(); do { ; } while (Dummy(f < 3, (f++) is var x1, x1, l, () => System.Console.WriteLine(x1))); System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 2 3 -- 1 2 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void For_01() { var source = @" public class X { public static void Main() { bool f = true; for (Dummy(f, (f ? 10 : 20) is var x0, x0); Dummy(f, (f ? 1 : 2) is var x1, x1); Dummy(f, (f ? 100 : 200) is var x2, x2), Dummy(true, null, x2)) { System.Console.WriteLine(x0); System.Console.WriteLine(x1); f = false; } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"10 1 10 1 200 200 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetPatternDeclarations(tree, "x0").Single(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(2, x0Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x0Decl, x0Ref); var x1Decl = GetPatternDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref); var x2Decl = GetPatternDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref); } [Fact] public void For_02() { var source = @" public class X { public static void Main() { bool f = true; for (Dummy(f, (f ? 10 : 20) is var x0, x0); Dummy(f, (f ? 1 : 2) is var x1, x1); f = false, Dummy(f, (f ? 100 : 200) is var x2, x2), Dummy(true, null, x2)) { System.Console.WriteLine(x0); System.Console.WriteLine(x1); } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"10 1 10 1 200 200 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetPatternDeclarations(tree, "x0").Single(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(2, x0Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x0Decl, x0Ref); var x1Decl = GetPatternDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref); var x2Decl = GetPatternDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref); } [Fact] public void For_03() { var source = @" public class X { public static void Main() { var l = new System.Collections.Generic.List<System.Action>(); for (bool f = 1 is var x0; Dummy(x0 < 3, x0*10 is var x1, x1); x0++) { l.Add(() => System.Console.WriteLine(""{0} {1}"", x0, x1)); } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"10 20 30 -- 3 10 3 20 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetPatternDeclarations(tree, "x0").ToArray(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(1, x0Decl.Length); Assert.Equal(4, x0Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x0Decl[0], x0Ref); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void For_04() { var source = @" public class X { public static void Main() { var l = new System.Collections.Generic.List<System.Action>(); for (bool f = 1 is var x0; Dummy(x0 < 3, x0*10 is var x1, x1, l, () => System.Console.WriteLine(""{0} {1}"", x0, x1)); x0++) { } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"10 20 30 -- 3 10 3 20 3 30 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetPatternDeclarations(tree, "x0").ToArray(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(1, x0Decl.Length); Assert.Equal(4, x0Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x0Decl[0], x0Ref); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void For_05() { var source = @" public class X { public static void Main() { var l = new System.Collections.Generic.List<System.Action>(); for (bool f = 1 is var x0; Dummy(x0 < 3, x0*10 is var x1, x1, l, () => System.Console.WriteLine(""{0} {1}"", x0, x1)); x0++) { l.Add(() => System.Console.WriteLine(""{0} {1}"", x0, x1)); } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"10 20 30 -- 3 10 3 10 3 20 3 20 3 30 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetPatternDeclarations(tree, "x0").ToArray(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(1, x0Decl.Length); Assert.Equal(5, x0Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x0Decl[0], x0Ref); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void Foreach_01() { var source = @" public class X { public static void Main() { bool f = true; foreach (var i in Dummy(3 is var x1, x1)) { System.Console.WriteLine(x1); } } static System.Collections.IEnumerable Dummy(object y, object z) { System.Console.WriteLine(z); return ""a""; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"3 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref); } [Fact] public void Lock_01() { var source = @" public class X { public static void Main() { lock (Dummy(""lock"" is var x1, x1)) { System.Console.WriteLine(x1); } System.Console.WriteLine(x1); } static object Dummy(object y, object z) { System.Console.WriteLine(z); return new object(); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"lock lock lock"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void Lock_02() { var source = @" public class X { public static void Main() { bool f = true; if (f) lock (Dummy(f, (f ? 1 : 2) is var x1, x1)) {} if (f) { lock (Dummy(f, (f ? 3 : 4) is var x1, x1)) {} } } static object Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0]); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]); } [Fact] public void Fixed_01() { var source = @" public unsafe class X { public static void Main() { fixed (int* p = Dummy(""fixed"" is var x1, x1)) { System.Console.WriteLine(x1); } } static int[] Dummy(object y, object z) { System.Console.WriteLine(z); return new int[1]; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe.WithAllowUnsafe(true)); CompileAndVerify(compilation, verify: Verification.Fails, expectedOutput: @"fixed fixed"); } [Fact] public void Yield_01() { var source = @" public class X { public static void Main() { foreach (var o in Test()) {} } static System.Collections.IEnumerable Test() { yield return Dummy(""yield1"" is var x1, x1); yield return Dummy(""yield2"" is var x2, x2); System.Console.WriteLine(x1); } static object Dummy(object y, object z) { System.Console.WriteLine(z); return new object(); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"yield1 yield2 yield1"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void Yield_02() { var source = @" public class X { public static void Main() { foreach (var o in Test()) {} } static System.Collections.IEnumerable Test() { bool f = true; if (f) yield return Dummy(""yield1"" is var x1, x1); if (f) { yield return Dummy(""yield2"" is var x1, x1); } } static object Dummy(object y, object z) { System.Console.WriteLine(z); return new object(); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"yield1 yield2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0]); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]); } [Fact] public void Return_01() { var source = @" public class X { public static void Main() { Test(); } static object Test() { return Dummy(""return"" is var x1, x1); } static object Dummy(object y, object z) { System.Console.WriteLine(z); return new object(); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"return"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").ToArray(); var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void Return_02() { var text = @" public class Cls { public static void Main() { Test0(true); Test0(false); } static object Test0(bool val) { if (val) return Test2(1 is var x1, x1); if (!val) { return Test2(2 is var x1, x1); } return null; } static object Test2(object x, object y) { System.Console.Write(y); return x; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: "12").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").ToArray(); var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0]); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]); } [Fact] public void Throw_01() { var source = @" public class X { public static void Main() { Test(); } static void Test() { try { throw Dummy(""throw"" is var x1, x1); } catch { } } static System.Exception Dummy(object y, object z) { System.Console.WriteLine(z); return new System.ArgumentException(); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"throw"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").ToArray(); var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void Throw_02() { var source = @" public class X { public static void Main() { Test(true); Test(false); } static void Test(bool val) { try { if (val) throw Dummy(""throw 1"" is var x1, x1); if (!val) { throw Dummy(""throw 2"" is var x1, x1); } } catch { } } static System.Exception Dummy(object y, object z) { System.Console.WriteLine(z); return new System.ArgumentException(); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"throw 1 throw 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").ToArray(); var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0]); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]); } [Fact] public void Catch_01() { var source = @" public class X { public static void Main() { try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(e is var x1, x1)) { System.Console.WriteLine(x1.GetType()); } } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref); } [Fact] public void Catch_02() { var source = @" public class X { public static void Main() { try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(e is var x1, x1)) { System.Action d = () => { System.Console.WriteLine(x1.GetType()); }; System.Console.WriteLine(x1.GetType()); d(); } } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException System.InvalidOperationException"); } [Fact] public void Catch_03() { var source = @" public class X { public static void Main() { try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(e is var x1, x1)) { System.Action d = () => { e = new System.NullReferenceException(); System.Console.WriteLine(x1.GetType()); }; System.Console.WriteLine(x1.GetType()); d(); System.Console.WriteLine(e.GetType()); } } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException System.InvalidOperationException System.NullReferenceException"); } [Fact] public void Catch_04() { var source = @" public class X { public static void Main() { try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(e is var x1, x1)) { System.Action d = () => { e = new System.NullReferenceException(); }; System.Console.WriteLine(x1.GetType()); d(); System.Console.WriteLine(e.GetType()); } } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException System.NullReferenceException"); } [Fact] public void Labeled_01() { var text = @" public class Cls { public static void Main() { a: Test1(2 is var x1); System.Console.WriteLine(x1); } static object Test1(bool x) { return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: "2").VerifyDiagnostics( // (6,1): warning CS0164: This label has not been referenced // a: Test1(2 is var x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(6, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").ToArray(); var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void Labeled_02() { var text = @" public class Cls { public static void Main() { Test0(); } static object Test0() { bool test = true; if (test) { a: Test2(2 is var x1, x1); } return null; } static object Test2(object x, object y) { System.Console.Write(y); return x; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: "2").VerifyDiagnostics( // (15,1): warning CS0164: This label has not been referenced // a: Test2(2 is var x1, x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(15, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").ToArray(); var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact, WorkItem(10465, "https://github.com/dotnet/roslyn/issues/10465")] public void Constants_Fail() { var source = @" using System; public class X { public static void Main() { Console.WriteLine(1L is string); // warning: type mismatch Console.WriteLine(1 is int[]); // warning: expression is never of the provided type Console.WriteLine(1L is string s); // error: type mismatch Console.WriteLine(1 is int[] a); // error: expression is never of the provided type } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (7,27): warning CS0184: The given expression is never of the provided ('string') type // Console.WriteLine(1L is string); // warning: type mismatch Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "1L is string").WithArguments("string").WithLocation(7, 27), // (8,27): warning CS0184: The given expression is never of the provided ('int[]') type // Console.WriteLine(1 is int[]); // warning: expression is never of the provided type Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "1 is int[]").WithArguments("int[]").WithLocation(8, 27), // (10,33): error CS8121: An expression of type 'long' cannot be handled by a pattern of type 'string'. // Console.WriteLine(1L is string s); // error: type mismatch Diagnostic(ErrorCode.ERR_PatternWrongType, "string").WithArguments("long", "string").WithLocation(10, 33), // (11,32): error CS8121: An expression of type 'int' cannot be handled by a pattern of type 'int[]'. // Console.WriteLine(1 is int[] a); // error: expression is never of the provided type Diagnostic(ErrorCode.ERR_PatternWrongType, "int[]").WithArguments("int", "int[]").WithLocation(11, 32) ); } [Fact, WorkItem(10465, "https://github.com/dotnet/roslyn/issues/10465")] public void Types_Pass() { var source = @" using System; public class X { public static void Main() { Console.WriteLine(1 is 1); // true Console.WriteLine(1L is int.MaxValue); // OK, but false Console.WriteLine(1 is int.MaxValue); // false Console.WriteLine(int.MaxValue is int.MaxValue); // true Console.WriteLine(""goo"" is System.String); // true Console.WriteLine(Int32.MaxValue is Int32.MaxValue); // true Console.WriteLine(new int[] {1, 2} is int[] a); // true object o = null; switch (o) { case int[] b: break; case int.MaxValue: // constant, not a type break; case int i: break; case null: Console.WriteLine(""null""); break; } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (7,27): warning CS8417: The given expression always matches the provided constant. // Console.WriteLine(1 is 1); // true Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesConstant, "1 is 1").WithLocation(7, 27), // (8,27): warning CS8416: The given expression never matches the provided pattern. // Console.WriteLine(1L is int.MaxValue); // OK, but false Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1L is int.MaxValue").WithLocation(8, 27), // (9,27): warning CS8416: The given expression never matches the provided pattern. // Console.WriteLine(1 is int.MaxValue); // false Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is int.MaxValue").WithLocation(9, 27), // (10,27): warning CS8417: The given expression always matches the provided constant. // Console.WriteLine(int.MaxValue is int.MaxValue); // true Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesConstant, "int.MaxValue is int.MaxValue").WithLocation(10, 27), // (11,27): warning CS0183: The given expression is always of the provided ('string') type // Console.WriteLine("goo" is System.String); // true Diagnostic(ErrorCode.WRN_IsAlwaysTrue, @"""goo"" is System.String").WithArguments("string").WithLocation(11, 27), // (12,27): warning CS8417: The given expression always matches the provided constant. // Console.WriteLine(Int32.MaxValue is Int32.MaxValue); // true Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesConstant, "Int32.MaxValue is Int32.MaxValue").WithLocation(12, 27) ); CompileAndVerify(compilation, expectedOutput: @"True False False True True True True null"); } [Fact, WorkItem(10459, "https://github.com/dotnet/roslyn/issues/10459")] public void Typeswitch_01() { var source = @" using System; public class X { public static void Main(string[] args) { switch (args.GetType()) { case typeof(string): Console.WriteLine(""string""); break; case typeof(string[]): Console.WriteLine(""string[]""); break; case null: Console.WriteLine(""null""); break; default: Console.WriteLine(""default""); break; } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (9,18): error CS0150: A constant value is expected // case typeof(string): Diagnostic(ErrorCode.ERR_ConstantExpected, "typeof(string)").WithLocation(9, 18), // (12,18): error CS0150: A constant value is expected // case typeof(string[]): Diagnostic(ErrorCode.ERR_ConstantExpected, "typeof(string[])").WithLocation(12, 18) ); // If we support switching on System.Type as proposed, the expectation would be // something like CompileAndVerify(compilation, expectedOutput: @"string[]"); } [Fact, WorkItem(10529, "https://github.com/dotnet/roslyn/issues/10529")] public void MissingTypeAndProperty() { var source = @" class Program { public static void Main(string[] args) { { if (obj.Property is var o) { } // `obj` doesn't exist. } { var obj = new object(); if (obj. is var o) { } } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (11,22): error CS1001: Identifier expected // if (obj. is var o) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, "is").WithLocation(11, 22), // (7,17): error CS0103: The name 'obj' does not exist in the current context // if (obj.Property is var o) { } // `obj` doesn't exist. Diagnostic(ErrorCode.ERR_NameNotInContext, "obj").WithArguments("obj").WithLocation(7, 17) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); foreach (var isExpression in tree.GetRoot().DescendantNodes().OfType<IsPatternExpressionSyntax>()) { var symbolInfo = model.GetSymbolInfo(isExpression.Expression); Assert.Null(symbolInfo.Symbol); Assert.True(symbolInfo.CandidateSymbols.IsDefaultOrEmpty); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); } } [Fact] public void MixedDecisionTree() { var source = @" using System; public class X { public static void Main() { M(null); M(1); M((byte)1); M((short)1); M(2); M((byte)2); M((short)2); M(""hmm""); M(""bar""); M(""baz""); M(6); } public static void M(object o) { switch (o) { case ""hmm"": Console.WriteLine(""hmm""); break; case null: Console.WriteLine(""null""); break; case 1: Console.WriteLine(""int 1""); break; case ((byte)1): Console.WriteLine(""byte 1""); break; case ((short)1): Console.WriteLine(""short 1""); break; case ""bar"": Console.WriteLine(""bar""); break; case object t when t != o: Console.WriteLine(""impossible""); break; case 2: Console.WriteLine(""int 2""); break; case ((byte)2): Console.WriteLine(""byte 2""); break; case ((short)2): Console.WriteLine(""short 2""); break; case ""baz"": Console.WriteLine(""baz""); break; default: Console.WriteLine(""other "" + o); break; } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: @"null int 1 byte 1 short 1 int 2 byte 2 short 2 hmm bar baz other 6"); } [Fact] public void SemanticAnalysisWithPatternInCsharp6() { var source = @"class Program { public static void Main(string[] args) { switch (args.Length) { case 1 when true: break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular6); compilation.VerifyDiagnostics( // (7,13): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // case 1 when true: Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "case 1 when true:").WithArguments("pattern matching", "7.0").WithLocation(7, 13) ); } [Fact, WorkItem(11379, "https://github.com/dotnet/roslyn/issues/11379")] public void DeclarationPatternWithStaticClass() { var source = @"class Program { public static void Main(string[] args) { object o = args; switch (o) { case StaticType t: break; } } } public static class StaticType { } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (8,18): error CS0723: Cannot declare a variable of static type 'StaticType' // case StaticType t: Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "StaticType").WithArguments("StaticType").WithLocation(8, 18) ); } [Fact] public void PatternVariablesAreMutable02() { var source = @"class Program { public static void Main(string[] args) { object o = "" whatever ""; if (o is string s) { s = s.Trim(); System.Console.WriteLine(s); } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: "whatever"); } [Fact, WorkItem(12996, "https://github.com/dotnet/roslyn/issues/12996")] public void TypeOfAVarPatternVariable() { var source = @" class Program { public static void Main(string[] args) { } public static void Test(int val) { if (val is var o1) { System.Console.WriteLine(o1); } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var tree = compilation.SyntaxTrees[0]; var model1 = compilation.GetSemanticModel(tree); var declaration = tree.GetRoot().DescendantNodes().OfType<IsPatternExpressionSyntax>().Single(); var o1 = GetReferences(tree, "o1").Single(); var typeInfo1 = model1.GetTypeInfo(declaration); Assert.Equal(SymbolKind.NamedType, typeInfo1.Type.Kind); Assert.Equal("System.Boolean", typeInfo1.Type.ToTestDisplayString()); typeInfo1 = model1.GetTypeInfo(o1); Assert.Equal(SymbolKind.NamedType, typeInfo1.Type.Kind); Assert.Equal("System.Int32", typeInfo1.Type.ToTestDisplayString()); var model2 = compilation.GetSemanticModel(tree); var typeInfo2 = model2.GetTypeInfo(o1); Assert.Equal(SymbolKind.NamedType, typeInfo2.Type.Kind); Assert.Equal("System.Int32", typeInfo2.Type.ToTestDisplayString()); } [Fact] [WorkItem(13417, "https://github.com/dotnet/roslyn/issues/13417")] public void FixedFieldSize() { var text = @" unsafe struct S { fixed int F1[3 is var x1 ? x1 : 3]; fixed int F2[3 is var x2 ? 3 : 3, x2]; } "; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); Assert.True(((ITypeSymbol)compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref).Type).IsErrorType()); VerifyModelNotSupported(model, x1Decl, x1Ref); var x2Decl = GetPatternDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelNotSupported(model, x2Decl, x2Ref); Assert.True(((ITypeSymbol)compilation.GetSemanticModel(tree).GetTypeInfo(x2Ref).Type).IsErrorType()); compilation.VerifyDiagnostics( // (5,17): error CS7092: A fixed buffer may only have one dimension. // fixed int F2[3 is var x2 ? 3 : 3, x2]; Diagnostic(ErrorCode.ERR_FixedBufferTooManyDimensions, "[3 is var x2 ? 3 : 3, x2]").WithLocation(5, 17), // (5,18): error CS0133: The expression being assigned to 'S.F2' must be constant // fixed int F2[3 is var x2 ? 3 : 3, x2]; Diagnostic(ErrorCode.ERR_NotConstantExpression, "3 is var x2 ? 3 : 3").WithArguments("S.F2").WithLocation(5, 18), // (4,18): error CS0133: The expression being assigned to 'S.F1' must be constant // fixed int F1[3 is var x1 ? x1 : 3]; Diagnostic(ErrorCode.ERR_NotConstantExpression, "3 is var x1 ? x1 : 3").WithArguments("S.F1").WithLocation(4, 18) ); } [Fact, WorkItem(13316, "https://github.com/dotnet/roslyn/issues/13316")] public void TypeAsExpressionInIsPattern() { var source = @"namespace CS7 { class T1 { public int a = 2; } class Program { static void Main(string[] args) { if (T1 is object i) { } } } }"; CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics( // (8,17): error CS0119: 'T1' is a type, which is not valid in the given context // if (T1 is object i) Diagnostic(ErrorCode.ERR_BadSKunknown, "T1").WithArguments("CS7.T1", "type").WithLocation(8, 17) ); } [Fact, WorkItem(13316, "https://github.com/dotnet/roslyn/issues/13316")] public void MethodGroupAsExpressionInIsPattern() { var source = @"namespace CS7 { class Program { const int T = 2; static void M(object o) { if (M is T) { } } } }"; CreateCompilation(source).VerifyDiagnostics( // (8,17): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // if (M is T) Diagnostic(ErrorCode.ERR_LambdaInIsAs, "M is T").WithLocation(8, 17) ); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(13383, "https://github.com/dotnet/roslyn/issues/13383")] public void MethodGroupAsExpressionInIsPatternBrokenCode() { var source = @"namespace CS7 { class Program { static void M(object o) { if (o.Equals is()) {} if (object.Equals is()) {} } } }"; var compilation = CreateCompilation(source).VerifyDiagnostics( // (7,17): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // if (o.Equals is()) {} Diagnostic(ErrorCode.ERR_LambdaInIsAs, "o.Equals is()").WithLocation(7, 17), // (8,17): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // if (object.Equals is()) {} Diagnostic(ErrorCode.ERR_LambdaInIsAs, "object.Equals is()").WithLocation(8, 17) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<IsPatternExpressionSyntax>().First(); Assert.Equal("o.Equals is()", node.ToString()); // https://github.com/dotnet/roslyn/issues/27749 : This syntax corresponds to a deconstruction pattern with zero elements, which is not yet supported in IOperation. // compilation.VerifyOperationTree(node, expectedOperationTree: //@" //IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'o.Equals is()') // Expression: // IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'o.Equals is()') // Children(1): // IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'o.Equals') // Children(1): // IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object, IsInvalid) (Syntax: 'o') // Pattern: //"); } [Fact, WorkItem(13383, "https://github.com/dotnet/roslyn/issues/13383")] public void MethodGroupAsExpressionInIsPatternBrokenCode2() { var source = @"namespace CS7 { class Program { static void M(object o) { if (null is()) {} if ((1, object.Equals) is()) {} } } }"; CreateCompilation(source).VerifyDiagnostics( // (7,17): error CS8117: Invalid operand for pattern match; value required, but found '<null>'. // if (null is()) {} Diagnostic(ErrorCode.ERR_BadPatternExpression, "null").WithArguments("<null>").WithLocation(7, 17), // (8,17): error CS0023: Operator 'is' cannot be applied to operand of type '(int, method group)' // if ((1, object.Equals) is()) {} Diagnostic(ErrorCode.ERR_BadUnaryOp, "(1, object.Equals) is()").WithArguments("is", "(int, method group)").WithLocation(8, 17) ); } [Fact, WorkItem(13723, "https://github.com/dotnet/roslyn/issues/13723")] [CompilerTrait(CompilerFeature.Tuples)] public void ExpressionWithoutAType() { var source = @" public class Vec { public static void Main() { if (null is 1) {} if (Main is 2) {} if (delegate {} is 3) {} if ((1, null) is 4) {} if (null is var x1) {} if (Main is var x2) {} if (delegate {} is var x3) {} if ((1, null) is var x4) {} } } "; CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics( // (6,13): error CS8117: Invalid operand for pattern match; value required, but found '<null>'. // if (null is 1) {} Diagnostic(ErrorCode.ERR_BadPatternExpression, "null").WithArguments("<null>").WithLocation(6, 13), // (7,13): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // if (Main is 2) {} Diagnostic(ErrorCode.ERR_LambdaInIsAs, "Main is 2").WithLocation(7, 13), // (8,13): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // if (delegate {} is 3) {} Diagnostic(ErrorCode.ERR_LambdaInIsAs, "delegate {} is 3").WithLocation(8, 13), // (8,25): warning CS8848: Operator 'is' cannot be used here due to precedence. Use parentheses to disambiguate. // if (delegate {} is 3) {} Diagnostic(ErrorCode.WRN_PrecedenceInversion, "is").WithArguments("is").WithLocation(8, 25), // (9,13): error CS0023: Operator 'is' cannot be applied to operand of type '(int, <null>)' // if ((1, null) is 4) {} Diagnostic(ErrorCode.ERR_BadUnaryOp, "(1, null) is 4").WithArguments("is", "(int, <null>)").WithLocation(9, 13), // (10,13): error CS8117: Invalid operand for pattern match; value required, but found '<null>'. // if (null is var x1) {} Diagnostic(ErrorCode.ERR_BadPatternExpression, "null").WithArguments("<null>").WithLocation(10, 13), // (11,13): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // if (Main is var x2) {} Diagnostic(ErrorCode.ERR_LambdaInIsAs, "Main is var x2").WithLocation(11, 13), // (12,13): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // if (delegate {} is var x3) {} Diagnostic(ErrorCode.ERR_LambdaInIsAs, "delegate {} is var x3").WithLocation(12, 13), // (12,25): warning CS8848: Operator 'is' cannot be used here due to precedence. Use parentheses to disambiguate. // if (delegate {} is var x3) {} Diagnostic(ErrorCode.WRN_PrecedenceInversion, "is").WithArguments("is").WithLocation(12, 25), // (13,13): error CS0023: Operator 'is' cannot be applied to operand of type '(int, <null>)' // if ((1, null) is var x4) {} Diagnostic(ErrorCode.ERR_BadUnaryOp, "(1, null) is var x4").WithArguments("is", "(int, <null>)").WithLocation(13, 13) ); } [Fact, WorkItem(13746, "https://github.com/dotnet/roslyn/issues/13746")] [CompilerTrait(CompilerFeature.Tuples)] public void ExpressionWithoutAType02() { var source = @" public class Program { public static void Main() { if ((1, null) is Program) {} } } "; CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics( // (6,13): error CS0023: Operator 'is' cannot be applied to operand of type '(int, <null>)' // if ((1, null) is Program) {} Diagnostic(ErrorCode.ERR_BadUnaryOp, "(1, null) is Program").WithArguments("is", "(int, <null>)").WithLocation(6, 13) ); } [Fact, WorkItem(15956, "https://github.com/dotnet/roslyn/issues/15956")] public void ThrowExpressionWithNullableDecimal() { var source = @" using System; public class ITest { public decimal Test() => 1m; } public class TestClass { public void Test(ITest test) { var result = test?.Test() ?? throw new Exception(); } }"; // DEBUG var compilation = CreateCompilation(source, options: TestOptions.DebugDll); compilation.VerifyDiagnostics(); compilation.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(compilation); verifier.VerifyIL("TestClass.Test", @"{ // Code size 18 (0x12) .maxstack 1 .locals init (decimal V_0, //result decimal V_1) IL_0000: nop IL_0001: ldarg.1 IL_0002: brtrue.s IL_000a IL_0004: newobj ""System.Exception..ctor()"" IL_0009: throw IL_000a: ldarg.1 IL_000b: call ""decimal ITest.Test()"" IL_0010: stloc.0 IL_0011: ret }"); // RELEASE compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); compilation.VerifyEmitDiagnostics(); verifier = CompileAndVerify(compilation); verifier.VerifyIL("TestClass.Test", @"{ // Code size 17 (0x11) .maxstack 1 IL_0000: ldarg.1 IL_0001: brtrue.s IL_0009 IL_0003: newobj ""System.Exception..ctor()"" IL_0008: throw IL_0009: ldarg.1 IL_000a: call ""decimal ITest.Test()"" IL_000f: pop IL_0010: ret }"); } [Fact, WorkItem(15956, "https://github.com/dotnet/roslyn/issues/15956")] public void ThrowExpressionWithNullableDateTime() { var source = @" using System; public class ITest { public DateTime Test() => new DateTime(2008, 5, 1, 8, 30, 52); } public class TestClass { public void Test(ITest test) { var result = test?.Test() ?? throw new Exception(); } }"; // DEBUG var compilation = CreateCompilation(source, options: TestOptions.DebugDll); compilation.VerifyDiagnostics(); compilation.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(compilation); verifier.VerifyIL("TestClass.Test", @"{ // Code size 18 (0x12) .maxstack 1 .locals init (System.DateTime V_0, //result System.DateTime V_1) IL_0000: nop IL_0001: ldarg.1 IL_0002: brtrue.s IL_000a IL_0004: newobj ""System.Exception..ctor()"" IL_0009: throw IL_000a: ldarg.1 IL_000b: call ""System.DateTime ITest.Test()"" IL_0010: stloc.0 IL_0011: ret }"); // RELEASE compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); compilation.VerifyEmitDiagnostics(); verifier = CompileAndVerify(compilation); verifier.VerifyIL("TestClass.Test", @"{ // Code size 17 (0x11) .maxstack 1 IL_0000: ldarg.1 IL_0001: brtrue.s IL_0009 IL_0003: newobj ""System.Exception..ctor()"" IL_0008: throw IL_0009: ldarg.1 IL_000a: call ""System.DateTime ITest.Test()"" IL_000f: pop IL_0010: ret }"); } [Fact] public void ThrowExpressionForParameterValidation() { var source = @"using System; class Program { public static void Main(string[] args) { foreach (var s in new[] { ""0123"", ""goo"" }) { Console.Write(s + "" ""); try { Console.WriteLine(Ver(s)); } catch (ArgumentException) { Console.WriteLine(""throws""); } } } static int Ver(string s) { var result = int.TryParse(s, out int k) ? k : throw new ArgumentException(nameof(s)); return k; // definitely assigned! } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"0123 123 goo throws"); } [Fact] public void ThrowExpressionWithNullable01() { var source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine(M(1)); try { Console.WriteLine(M(null)); } catch (Exception) { Console.WriteLine(""thrown""); } } static int M(int? data) { return data ?? throw null; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"1 thrown"); } [Fact] public void ThrowExpressionWithNullable02() { var source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine(M(1)); try { Console.WriteLine(M(null)); } catch (Exception) { Console.WriteLine(""thrown""); } } static string M(object data) { return data?.ToString() ?? throw null; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"1 thrown"); } [Fact] public void ThrowExpressionWithNullable03() { var source = @"using System; using System.Threading.Tasks; class Program { public static void Main(string[] args) { MainAsync().Wait(); } static async Task MainAsync() { foreach (var i in new[] { 1, 2 }) { try { var used = (await Goo(i))?.ToString() ?? throw await Bar(i); } catch (Exception ex) { Console.WriteLine(""thrown "" + ex.Message); } } } static async Task<object> Goo(int i) { await Task.Yield(); return (i == 1) ? i : (object)null; } static async Task<Exception> Bar(int i) { await Task.Yield(); Console.WriteLine(""making exception "" + i); return new Exception(i.ToString()); } } "; var compilation = CreateEmptyCompilation(source, options: TestOptions.DebugExe, references: new[] { MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929 }); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"making exception 2 thrown 2"); } [Fact] public void ThrowExpressionPrecedence01() { var source = @"using System; class Program { public static void Main(string[] args) { Exception ex = null; try { // The ?? operator is right-associative, even under 'throw' ex = ex ?? throw ex ?? throw new ArgumentException(""blue""); } catch (ArgumentException x) { Console.WriteLine(x.Message); } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"blue"); } [Fact] public void ThrowExpressionPrecedence02() { var source = @"using System; class Program { public static void Main(string[] args) { MyException ex = null; try { // Throw expression binds looser than + ex = ex ?? throw ex + 1; } catch (MyException x) { Console.WriteLine(x.Message); } } } class MyException : Exception { public MyException(string message) : base(message) {} public static MyException operator +(MyException left, int right) { return new MyException(""green""); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"green"); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void IsPatternPrecedence() { var source = @"using System; class Program { const bool B = true; const int One = 1; public static void Main(string[] args) { object a = null; B c = null; Console.WriteLine(a is B & c); // prints 5 (correct) Console.WriteLine(a is B > c); // prints 6 (correct) Console.WriteLine(a is B < c); // was syntax error but should print 7 Console.WriteLine(3 is One + 2); // should print True Console.WriteLine(One + 2 is 3); // should print True } } class B { public static int operator &(bool left, B right) => 5; public static int operator >(bool left, B right) => 6; public static int operator <(bool left, B right) => 7; public static int operator +(bool left, B right) => 8; } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular6).VerifyDiagnostics( // (15,27): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // Console.WriteLine(3 is One + 2); // should print True Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "3 is One + 2").WithArguments("pattern matching", "7.0").WithLocation(15, 27), // (16,27): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // Console.WriteLine(One + 2 is 3); // should print True Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "One + 2 is 3").WithArguments("pattern matching", "7.0").WithLocation(16, 27), // (15,27): warning CS8417: The given expression always matches the provided constant. // Console.WriteLine(3 is One + 2); // should print True Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesConstant, "3 is One + 2").WithLocation(15, 27), // (16,27): warning CS8417: The given expression always matches the provided constant. // Console.WriteLine(One + 2 is 3); // should print True Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesConstant, "One + 2 is 3").WithLocation(16, 27) ); var expectedOutput = @"5 6 7 True True"; compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (15,27): warning CS8417: The given expression always matches the provided constant. // Console.WriteLine(3 is One + 2); // should print True Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesConstant, "3 is One + 2").WithLocation(15, 27), // (16,27): warning CS8417: The given expression always matches the provided constant. // Console.WriteLine(One + 2 is 3); // should print True Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesConstant, "One + 2 is 3").WithLocation(16, 27) ); var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void IsPatternPrecedence02() { var source = @"using System; class Program { public static void Main(string[] args) { foreach (object A in new[] { null, new B<C,D>() }) { // pass one argument, a pattern-matching operation M(A is B < C, D > E); switch (A) { case B < C, D > F: Console.WriteLine(""yes""); break; default: Console.WriteLine(""no""); break; } } } static void M(object o) { Console.WriteLine(o); } } class B<C,D> { } class C {} class D {} "; var expectedOutput = @"False no True yes"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void IsPatternPrecedence03() { var source = @"using System; class Program { public static void Main(string[] args) { object A = new B<C, D>(); Console.WriteLine(A is B < C, D > E); Console.WriteLine(A as B < C, D > ?? string.Empty); } } class B<C,D> { public static implicit operator string(B<C,D> b) => nameof(B<C,D>); } class C {} class D {} "; var expectedOutput = @"True B"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); SyntaxFactory.ParseExpression("A is B < C, D > E").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("A as B < C, D > E").GetDiagnostics().Verify( // (1,1): error CS1073: Unexpected token 'E' // A as B < C, D > E Diagnostic(ErrorCode.ERR_UnexpectedToken, "A as B < C, D >").WithArguments("E").WithLocation(1, 1) ); SyntaxFactory.ParseExpression("A as B < C, D > ?? string.Empty").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("A is B < C, D > ?? string.Empty").GetDiagnostics().Verify( // (1,1): error CS1073: Unexpected token ',' // A is B < C, D > ?? string.Empty Diagnostic(ErrorCode.ERR_UnexpectedToken, "A is B < C").WithArguments(",").WithLocation(1, 1) ); } [Fact, WorkItem(14636, "https://github.com/dotnet/roslyn/issues/14636")] public void NameofPattern() { var source = @"using System; class Program { public static void Main(string[] args) { M(""a""); M(""b""); M(null); M(new nameof()); } public static void M(object a) { Console.WriteLine(a is nameof(a)); Console.WriteLine(a is nameof); } } class nameof { } "; var expectedOutput = @"True False False False False False False True"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact, WorkItem(14825, "https://github.com/dotnet/roslyn/issues/14825")] public void PatternVarDeclaredInReceiverUsedInArgument() { var source = @"using System.Linq; public class C { public string[] Goo2(out string x) { x = """"; return null; } public string[] Goo3(bool b) { return null; } public string[] Goo5(string u) { return null; } public void Test() { var t1 = Goo2(out var x1).Concat(Goo5(x1)); var t2 = Goo3(t1 is var x2).Concat(Goo5(x2.First())); } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x2Decl = GetPatternDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref); Assert.Equal("System.Collections.Generic.IEnumerable<System.String>", model.GetTypeInfo(x2Ref).Type.ToTestDisplayString()); } [Fact] public void DiscardInPattern() { var source = @" using static System.Console; public class C { public static void Main() { int i = 3; Write($""is int _: {i is int _}, ""); Write($""is var _: {i is var _}, ""); switch (3) { case int _: Write(""case int _, ""); break; } switch (3L) { case var _: Write(""case var _""); break; } } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "is int _: True, is var _: True, case int _, case var _"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).First(); Assert.Null(model.GetDeclaredSymbol(discard1)); var declaration1 = (DeclarationPatternSyntax)discard1.Parent; Assert.Equal("int _", declaration1.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration1).Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration1.Type).Type.ToTestDisplayString()); var discard2 = GetDiscardDesignations(tree).Skip(1).First(); Assert.Null(model.GetDeclaredSymbol(discard2)); Assert.Null(model.GetSymbolInfo(discard2).Symbol); var declaration2 = (VarPatternSyntax)discard2.Parent; Assert.Equal("var _", declaration2.ToString()); Assert.Null(model.GetSymbolInfo(declaration2).Symbol); var discard3 = GetDiscardDesignations(tree).Skip(2).First(); Assert.Null(model.GetDeclaredSymbol(discard3)); var declaration3 = (DeclarationPatternSyntax)discard3.Parent; Assert.Equal("int _", declaration3.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration3).Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration3.Type).Type.ToTestDisplayString()); var discard4 = GetDiscardDesignations(tree).Skip(3).First(); Assert.Null(model.GetDeclaredSymbol(discard4)); var declaration4 = (VarPatternSyntax)discard4.Parent; Assert.Equal("var _", declaration4.ToString()); } [Fact] public void ShortDiscardInPattern() { var source = @" using static System.Console; public class C { public static void Main() { int i = 3; Write($""is _: {i is _}, ""); switch (3) { case _: Write(""case _""); break; } } } "; CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (8,29): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?) // Write($"is _: {i is _}, "); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(8, 29), // (11,18): error CS0103: The name '_' does not exist in the current context // case _: Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(11, 18) ); CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (8,29): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?) // Write($"is _: {i is _}, "); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(8, 29), // (11,18): error CS0103: The name '_' does not exist in the current context // case _: Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(11, 18) ); } [Fact] public void UnderscoreInPattern2() { var source = @" using static System.Console; public class C { public static void Main() { int i = 3; int _ = 4; Write($""is _: {i is _}, ""); switch (3) { case _: Write(""case _""); break; } } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); compilation.VerifyDiagnostics( // (9,29): error CS0118: '_' is a variable but is used like a type // Write($"is _: {i is _}, "); Diagnostic(ErrorCode.ERR_BadSKknown, "_").WithArguments("_", "variable", "type").WithLocation(9, 29), // (12,18): error CS0150: A constant value is expected // case _: Diagnostic(ErrorCode.ERR_ConstantExpected, "_").WithLocation(12, 18) ); } [Fact] public void UnderscoreInPattern() { var source = @" using static System.Console; public class C { public static void Main() { int i = 3; if (i is int _) { Write(_); } if (i is var _) { Write(_); } switch (3) { case int _: Write(_); break; } switch (3) { case var _: Write(_); break; } } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (8,33): error CS0103: The name '_' does not exist in the current context // if (i is int _) { Write(_); } Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(8, 33), // (9,33): error CS0103: The name '_' does not exist in the current context // if (i is var _) { Write(_); } Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(9, 33), // (13,23): error CS0103: The name '_' does not exist in the current context // Write(_); Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(13, 23), // (19,23): error CS0103: The name '_' does not exist in the current context // Write(_); Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(19, 23) ); } [Fact] public void PointerTypeInPattern() { // pointer types are not supported in patterns. Therefore an attempt to use // a pointer type will be interpreted by the parser as a multiplication // (i.e. an expression that is a constant pattern rather than a declaration // pattern) var source = @" public class var {} unsafe public class Typ { public static void Main(int* a, var* c, Typ* e) { { if (a is int* b) {} if (c is var* d) {} if (e is Typ* f) {} } { switch (a) { case int* b: break; } switch (c) { case var* d: break; } switch (e) { case Typ* f: break; } } } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugDll); compilation.VerifyDiagnostics( // (8,22): error CS1525: Invalid expression term 'int' // if (a is int* b) {} Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(8, 22), // (13,31): error CS1525: Invalid expression term 'int' // switch (a) { case int* b: break; } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(13, 31), // (5,42): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('var') // public static void Main(int* a, var* c, Typ* e) Diagnostic(ErrorCode.ERR_ManagedAddr, "c").WithArguments("var").WithLocation(5, 42), // (5,50): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('Typ') // public static void Main(int* a, var* c, Typ* e) Diagnostic(ErrorCode.ERR_ManagedAddr, "e").WithArguments("Typ").WithLocation(5, 50), // (8,27): error CS0103: The name 'b' does not exist in the current context // if (a is int* b) {} Diagnostic(ErrorCode.ERR_NameNotInContext, "b").WithArguments("b").WithLocation(8, 27), // (9,22): error CS0119: 'var' is a type, which is not valid in the given context // if (c is var* d) {} Diagnostic(ErrorCode.ERR_BadSKunknown, "var").WithArguments("var", "type").WithLocation(9, 22), // (9,27): error CS0103: The name 'd' does not exist in the current context // if (c is var* d) {} Diagnostic(ErrorCode.ERR_NameNotInContext, "d").WithArguments("d").WithLocation(9, 27), // (10,22): error CS0119: 'Typ' is a type, which is not valid in the given context // if (e is Typ* f) {} Diagnostic(ErrorCode.ERR_BadSKunknown, "Typ").WithArguments("Typ", "type").WithLocation(10, 22), // (10,27): error CS0103: The name 'f' does not exist in the current context // if (e is Typ* f) {} Diagnostic(ErrorCode.ERR_NameNotInContext, "f").WithArguments("f").WithLocation(10, 27), // (13,36): error CS0103: The name 'b' does not exist in the current context // switch (a) { case int* b: break; } Diagnostic(ErrorCode.ERR_NameNotInContext, "b").WithArguments("b").WithLocation(13, 36), // (14,31): error CS0119: 'var' is a type, which is not valid in the given context // switch (c) { case var* d: break; } Diagnostic(ErrorCode.ERR_BadSKunknown, "var").WithArguments("var", "type").WithLocation(14, 31), // (14,36): error CS0103: The name 'd' does not exist in the current context // switch (c) { case var* d: break; } Diagnostic(ErrorCode.ERR_NameNotInContext, "d").WithArguments("d").WithLocation(14, 36), // (15,31): error CS0119: 'Typ' is a type, which is not valid in the given context // switch (e) { case Typ* f: break; } Diagnostic(ErrorCode.ERR_BadSKunknown, "Typ").WithArguments("Typ", "type").WithLocation(15, 31), // (15,36): error CS0103: The name 'f' does not exist in the current context // switch (e) { case Typ* f: break; } Diagnostic(ErrorCode.ERR_NameNotInContext, "f").WithArguments("f").WithLocation(15, 36) ); } [Fact] [WorkItem(16513, "https://github.com/dotnet/roslyn/issues/16513")] public void OrderOfPatternOperands() { var source = @" using System; class Program { public static void Main(string[] args) { object c = new C(); Console.WriteLine(c is 3); c = 2; Console.WriteLine(c is 3); c = 3; Console.WriteLine(c is 3); } } class C { override public bool Equals(object other) { return other is int x; } override public int GetHashCode() => 0; } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var comp = CompileAndVerify(compilation, expectedOutput: @"False False True"); } [Fact] public void MultiplyInPattern() { // pointer types are not supported in patterns. Therefore an attempt to use // a pointer type will be interpreted by the parser as a multiplication // (i.e. an expression that is a constant pattern rather than a declaration // pattern) var source = @" public class Program { public static void Main() { const int two = 2; const int three = 3; int six = two * three; System.Console.WriteLine(six is two * three); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var comp = CompileAndVerify(compilation, expectedOutput: "True"); } [Fact] public void ColorColorConstantPattern() { var source = @" public class Program { public static Color Color { get; } public static void M(object o) { System.Console.WriteLine(o is Color.Constant); } public static void Main() { M(Color.Constant); } } public class Color { public const string Constant = ""abc""; } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var comp = CompileAndVerify(compilation, expectedOutput: "True"); } [Fact] [WorkItem(336030, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/336030")] public void NullOperand() { var source = @" class C { void M() { System.Console.Write(null is Missing x); System.Console.Write(null is Missing); switch(null) { case Missing: case Missing y: break; } } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,30): error CS8117: Invalid operand for pattern match; value required, but found '<null>'. // System.Console.Write(null is Missing x); Diagnostic(ErrorCode.ERR_BadPatternExpression, "null").WithArguments("<null>").WithLocation(6, 30), // (6,38): error CS0246: The type or namespace name 'Missing' could not be found (are you missing a using directive or an assembly reference?) // System.Console.Write(null is Missing x); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Missing").WithArguments("Missing").WithLocation(6, 38), // (7,38): error CS0246: The type or namespace name 'Missing' could not be found (are you missing a using directive or an assembly reference?) // System.Console.Write(null is Missing); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Missing").WithArguments("Missing").WithLocation(7, 38), // (8,16): error CS8119: The switch expression must be a value; found '<null>'. // switch(null) Diagnostic(ErrorCode.ERR_SwitchExpressionValueExpected, "null").WithArguments("<null>").WithLocation(8, 16), // (10,18): error CS0103: The name 'Missing' does not exist in the current context // case Missing: Diagnostic(ErrorCode.ERR_NameNotInContext, "Missing").WithArguments("Missing").WithLocation(10, 18), // (11,18): error CS0246: The type or namespace name 'Missing' could not be found (are you missing a using directive or an assembly reference?) // case Missing y: Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Missing").WithArguments("Missing").WithLocation(11, 18) ); } [Fact] [WorkItem(336030, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=336030")] [WorkItem(294570, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=294570")] public void Fuzz46() { var program = @" public class Program46 { public static void Main(string[] args) { switch ((() => 1)) { case int x4: case string x9: case M: case ((int)M()): break; } } private static object M() => null; }"; CreateCompilation(program).VerifyDiagnostics( // (6,17): error CS8119: The switch expression must be a value; found 'lambda expression'. // switch ((() => 1)) Diagnostic(ErrorCode.ERR_SwitchExpressionValueExpected, "(() => 1)").WithArguments("lambda expression").WithLocation(6, 17), // (10,18): error CS0150: A constant value is expected // case M: Diagnostic(ErrorCode.ERR_ConstantExpected, "M").WithLocation(10, 18), // (11,19): error CS0150: A constant value is expected // case ((int)M()): Diagnostic(ErrorCode.ERR_ConstantExpected, "(int)M()").WithLocation(11, 19) ); } [Fact] [WorkItem(363714, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=363714")] public void Fuzz46b() { var program = @" public class Program46 { public static void Main(string[] args) { switch ((() => 1)) { case M: break; } } private static object M() => null; }"; CreateCompilation(program).VerifyDiagnostics( // (6,17): error CS8119: The switch expression must be a value; found 'lambda expression'. // switch ((() => 1)) Diagnostic(ErrorCode.ERR_SwitchExpressionValueExpected, "(() => 1)").WithArguments("lambda expression").WithLocation(6, 17), // (8,18): error CS0150: A constant value is expected // case M: Diagnostic(ErrorCode.ERR_ConstantExpected, "M").WithLocation(8, 18) ); } [Fact] [WorkItem(336030, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=336030")] public void Fuzz401() { var program = @" public class Program401 { public static void Main(string[] args) { if (null is M) {} } private static object M() => null; }"; CreateCompilation(program).VerifyDiagnostics( // (6,13): error CS8117: Invalid operand for pattern match; value required, but found '<null>'. // if (null is M) {} Diagnostic(ErrorCode.ERR_BadPatternExpression, "null").WithArguments("<null>").WithLocation(6, 13), // (6,21): error CS0150: A constant value is expected // if (null is M) {} Diagnostic(ErrorCode.ERR_ConstantExpected, "M").WithLocation(6, 21) ); } [Fact] [WorkItem(364165, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=364165")] [WorkItem(16296, "https://github.com/dotnet/roslyn/issues/16296")] public void Fuzz1717() { var program = @" public class Program1717 { public static void Main(string[] args) { switch (default(int?)) { case 2: break; case double.NaN: break; case var x9: case string _: break; } } private static object M() => null; }"; CreateCompilation(program).VerifyDiagnostics( // (10,18): error CS0266: Cannot implicitly convert type 'double' to 'int?'. An explicit conversion exists (are you missing a cast?) // case double.NaN: Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "double.NaN").WithArguments("double", "int?").WithLocation(10, 18), // (13,18): error CS8121: An expression of type 'int?' cannot be handled by a pattern of type 'string'. // case string _: Diagnostic(ErrorCode.ERR_PatternWrongType, "string").WithArguments("int?", "string").WithLocation(13, 18) ); } [Fact, WorkItem(16559, "https://github.com/dotnet/roslyn/issues/16559")] public void CasePatternVariableUsedInCaseExpression() { var program = @" public class Program5815 { public static void Main(object o) { switch (o) { case Color Color: case Color? Color2: break; } } private static object M() => null; }"; var compilation = CreateCompilation(program).VerifyDiagnostics( // (9,32): error CS1525: Invalid expression term 'break' // case Color? Color2: Diagnostic(ErrorCode.ERR_InvalidExprTerm, "").WithArguments("break").WithLocation(9, 32), // (9,32): error CS1003: Syntax error, ':' expected // case Color? Color2: Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(":", "break").WithLocation(9, 32), // (8,18): error CS0118: 'Color' is a variable but is used like a type // case Color Color: Diagnostic(ErrorCode.ERR_BadSKknown, "Color").WithArguments("Color", "variable", "type").WithLocation(8, 18), // (9,25): error CS0103: The name 'Color2' does not exist in the current context // case Color? Color2: Diagnostic(ErrorCode.ERR_NameNotInContext, "Color2").WithArguments("Color2").WithLocation(9, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var colorDecl = GetPatternDeclarations(tree, "Color").ToArray(); var colorRef = GetReferences(tree, "Color").ToArray(); Assert.Equal(1, colorDecl.Length); Assert.Equal(2, colorRef.Length); Assert.Null(model.GetSymbolInfo(colorRef[0]).Symbol); VerifyModelForDeclarationOrVarSimplePattern(model, colorDecl[0], colorRef[1]); } [Fact, WorkItem(16559, "https://github.com/dotnet/roslyn/issues/16559")] public void Fuzz5815() { var program = @" public class Program5815 { public static void Main(string[] args) { switch ((int)M()) { case var x3: case true ? x3 : 4: break; } } private static object M() => null; }"; var compilation = CreateCompilation(program).VerifyDiagnostics( // (9,18): error CS0150: A constant value is expected // case true ? x3 : 4: Diagnostic(ErrorCode.ERR_ConstantExpected, "true ? x3 : 4").WithLocation(9, 18), // (9,25): error CS0165: Use of unassigned local variable 'x3' // case true ? x3 : 4: Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(9, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetPatternDeclarations(tree, "x3").ToArray(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(1, x3Decl.Length); Assert.Equal(1, x3Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl[0], x3Ref); } [Fact] public void Fuzz_Conjunction_01() { var program = @" public class Program { public static void Main(string[] args) { if (((int?)1) is {} and 1) { } } }"; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( ); } [Fact] public void Fuzz_738490379() { var program = @" public class Program738490379 { public static void Main(string[] args) { if (NotFound is var (M, not int _ or NotFound _) { }) {} } private static object M() => null; }"; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (6,13): error CS0841: Cannot use local variable 'NotFound' before it is declared // if (NotFound is var (M, not int _ or NotFound _) { }) {} Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "NotFound").WithArguments("NotFound").WithLocation(6, 13), // (6,37): error CS1026: ) expected // if (NotFound is var (M, not int _ or NotFound _) { }) {} Diagnostic(ErrorCode.ERR_CloseParenExpected, "int").WithLocation(6, 37), // (6,37): error CS1026: ) expected // if (NotFound is var (M, not int _ or NotFound _) { }) {} Diagnostic(ErrorCode.ERR_CloseParenExpected, "int").WithLocation(6, 37), // (6,37): error CS1023: Embedded statement cannot be a declaration or labeled statement // if (NotFound is var (M, not int _ or NotFound _) { }) {} Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "int _ ").WithLocation(6, 37), // (6,41): warning CS0168: The variable '_' is declared but never used // if (NotFound is var (M, not int _ or NotFound _) { }) {} Diagnostic(ErrorCode.WRN_UnreferencedVar, "_").WithArguments("_").WithLocation(6, 41), // (6,43): error CS1002: ; expected // if (NotFound is var (M, not int _ or NotFound _) { }) {} Diagnostic(ErrorCode.ERR_SemicolonExpected, "or").WithLocation(6, 43), // (6,43): error CS0246: The type or namespace name 'or' could not be found (are you missing a using directive or an assembly reference?) // if (NotFound is var (M, not int _ or NotFound _) { }) {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "or").WithArguments("or").WithLocation(6, 43), // (6,55): error CS1002: ; expected // if (NotFound is var (M, not int _ or NotFound _) { }) {} Diagnostic(ErrorCode.ERR_SemicolonExpected, "_").WithLocation(6, 55), // (6,55): error CS0103: The name '_' does not exist in the current context // if (NotFound is var (M, not int _ or NotFound _) { }) {} Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(6, 55), // (6,56): error CS1002: ; expected // if (NotFound is var (M, not int _ or NotFound _) { }) {} Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(6, 56), // (6,56): error CS1513: } expected // if (NotFound is var (M, not int _ or NotFound _) { }) {} Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(6, 56), // (6,62): error CS1513: } expected // if (NotFound is var (M, not int _ or NotFound _) { }) {} Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(6, 62) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/16721")] public void Fuzz() { const int numTests = 1200000; int dt = (int)Math.Abs(DateTime.Now.Ticks % 1000000000); for (int i = 1; i < numTests; i++) { PatternMatchingFuzz(i + dt); } } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/16721")] public void MultiFuzz() { // Just like Fuzz(), but take advantage of concurrency on the test host. const int numTasks = 300; const int numTestsPerTask = 4000; int dt = (int)Math.Abs(DateTime.Now.Ticks % 1000000000); var tasks = Enumerable.Range(0, numTasks).Select(t => Task.Run(() => { int k = dt + t * numTestsPerTask; for (int i = 1; i < numTestsPerTask; i++) { PatternMatchingFuzz(i + k); } })); Task.WaitAll(tasks.ToArray()); } private static void PatternMatchingFuzz(int dt) { Random r = new Random(dt); // generate a pattern-matching switch randomly from templates string[] expressions = new[] { "M", // a method group "(() => 1)", // a lambda expression "1", // a constant "2", // a constant "null", // the null constant "default(int?)", // a null constant of type int? "((int?)1)", // a constant of type int? "M()", // a method invocation "double.NaN", // a scary constant "1.1", // a double constant "NotFound" // an unbindable expression }; string Expression() { int index = r.Next(expressions.Length + 1) - 1; return (index < 0) ? $"(({Type()})M())" : expressions[index]; } string[] types = new[] { "object", "var", "int", "int?", "double", "string", "NotFound" }; string Type() => types[r.Next(types.Length)]; string Pattern(int d = 5) { switch (r.Next(d <= 1 ? 9 : 12)) { default: return Expression(); // a "constant" pattern case 3: case 4: return Type(); case 5: return Type() + " _"; case 6: return Type() + " x" + r.Next(10); case 7: return "not " + Pattern(d - 1); case 8: return "(" + Pattern(d - 1) + ")"; case 9: return makeRecursivePattern(d); case 10: return Pattern(d - 1) + " and " + Pattern(d - 1); case 11: return Pattern(d - 1) + " or " + Pattern(d - 1); } string makeRecursivePattern(int d) { while (true) { bool haveParens = r.Next(2) == 0; bool haveCurlies = r.Next(2) == 0; if (!haveParens && !haveCurlies) continue; bool haveType = r.Next(2) == 0; bool haveIdentifier = r.Next(2) == 0; return $"{(haveType ? Type() : null)} {(haveParens ? $"({makePatternList(d - 1, false)})" : null)} {(haveCurlies ? $"{"{ "}{makePatternList(d - 1, true)}{" }"}" : null)} {(haveIdentifier ? " x" + r.Next(10) : null)}"; } } string makePatternList(int d, bool propNames) { return string.Join(", ", Enumerable.Range(0, r.Next(3)).Select(i => $"{(propNames ? $"P{r.Next(10)}: " : null)}{Pattern(d)}")); } } string body = @" public class Program{0} {{ public static void Main(string[] args) {{ {1} }} private static object M() => null; }}"; var statement = new StringBuilder(); switch (r.Next(2)) { case 0: // test the "is-pattern" expression statement.Append($"if ({Expression()} is {Pattern()}) {{}}"); break; case 1: // test the pattern switch statement statement.AppendLine($"switch ({Expression()})"); statement.AppendLine("{"); var nCases = r.Next(5); for (int i = 1; i <= nCases; i++) { statement.AppendLine($" case {Pattern()}:"); if (i == nCases || r.Next(2) == 0) { statement.AppendLine($" break;"); } } statement.AppendLine("}"); break; default: throw null; } var program = string.Format(body, dt, statement); CreateCompilation(program).GetDiagnostics(); } [Fact, WorkItem(16671, "https://github.com/dotnet/roslyn/issues/16671")] public void TypeParameterSubsumption01() { var program = @" using System; public class Program { public static void Main(string[] args) { PatternMatching<Base, Derived>(new Base()); PatternMatching<Base, Derived>(new Derived()); PatternMatching<Base, Derived>(null); PatternMatching<object, int>(new object()); PatternMatching<object, int>(2); PatternMatching<object, int>(null); PatternMatching<object, int?>(new object()); PatternMatching<object, int?>(2); PatternMatching<object, int?>(null); } static void PatternMatching<TBase, TDerived>(TBase o) where TDerived : TBase { switch (o) { case TDerived td: Console.WriteLine(nameof(TDerived)); break; case TBase tb: Console.WriteLine(nameof(TBase)); break; default: Console.WriteLine(""Neither""); break; } } } class Base { } class Derived : Base { } "; var compilation = CreateCompilation(program, options: TestOptions.DebugExe).VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"TBase TDerived Neither TBase TDerived Neither TBase TDerived Neither"); } [Fact, WorkItem(16671, "https://github.com/dotnet/roslyn/issues/16671")] public void TypeParameterSubsumption02() { var program = @" using System; public class Program { static void PatternMatching<TBase, TDerived>(TBase o) where TDerived : TBase { switch (o) { case TBase tb: Console.WriteLine(nameof(TBase)); break; case TDerived td: Console.WriteLine(nameof(TDerived)); break; default: Console.WriteLine(""Neither""); break; } } } class Base { } class Derived : Base { } "; var compilation = CreateCompilation(program).VerifyDiagnostics( // (12,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match. // case TDerived td: Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "TDerived td").WithLocation(12, 18) ); } [Fact, WorkItem(16688, "https://github.com/dotnet/roslyn/issues/16688")] public void TypeParameterSubsumption03() { var program = @" using System.Collections.Generic; public class Program { private static void Pattern<T>(T thing) where T : class { switch (thing) { case T tThing: break; case IEnumerable<object> s: break; } } } "; var compilation = CreateCompilation(program).VerifyDiagnostics( // (11,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match. // case IEnumerable<object> s: Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "IEnumerable<object> s").WithLocation(11, 18) ); } [Fact, WorkItem(16696, "https://github.com/dotnet/roslyn/issues/16696")] public void TypeParameterSubsumption04() { var program = @" using System; using System.Collections.Generic; public class Program { private static int Pattern1<TBase, TDerived>(object thing) where TBase : class where TDerived : TBase { switch (thing) { case IEnumerable<TBase> sequence: return 1; // IEnumerable<TBase> does not subsume IEnumerable<TDerived> because TDerived may be a value type. case IEnumerable<TDerived> derivedSequence: return 2; default: return 3; } } private static int Pattern2<TBase, TDerived>(object thing) where TBase : class where TDerived : TBase { switch (thing) { case IEnumerable<object> s: return 1; // IEnumerable<object> does not subsume IEnumerable<TDerived> because TDerived may be a value type. case IEnumerable<TDerived> derivedSequence: return 2; default: return 3; } } public static void Main(string[] args) { Console.WriteLine(Pattern1<object, int>(new List<object>())); Console.WriteLine(Pattern1<object, int>(new List<int>())); Console.WriteLine(Pattern1<object, int>(null)); Console.WriteLine(Pattern2<object, int>(new List<object>())); Console.WriteLine(Pattern2<object, int>(new List<int>())); Console.WriteLine(Pattern2<object, int>(null)); } } "; var compilation = CreateCompilation(program, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"1 2 3 1 2 3"); } [Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")] public void TypeParameterSubsumption05() { var program = @" public class Program { static void M<T, U>(T t, U u) where T : U { switch(""test"") { case U uu: break; case T tt: // Produces a diagnostic about subsumption/unreachability break; } } } "; CreateCompilation(program, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7).VerifyDiagnostics( // (8,18): error CS8314: An expression of type 'string' cannot be handled by a pattern of type 'U' in C# 7.0. Please use language version 7.1 or greater. // case U uu: Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "U").WithArguments("string", "U", "7.0", "7.1").WithLocation(8, 18), // (10,18): error CS8314: An expression of type 'string' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater. // case T tt: // Produces a diagnostic about subsumption/unreachability Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("string", "T", "7.0", "7.1").WithLocation(10, 18) ); CreateCompilation(program, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_1).VerifyDiagnostics( // (10,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match. // case T tt: // Produces a diagnostic about subsumption/unreachability Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "T tt").WithLocation(10, 18) ); } [Fact, WorkItem(17103, "https://github.com/dotnet/roslyn/issues/17103")] public void IsConstantPatternConversion_Positive() { var source = @"using System; public class Program { public static void Main() { { byte b = 12; Console.WriteLine(b is 12); // True Console.WriteLine(b is 13); // False Console.WriteLine(b is (int)12L); // True Console.WriteLine(b is (int)13L); // False } bool Is42(byte b) => b is 42; Console.WriteLine(Is42(42)); Console.WriteLine(Is42(43)); Console.WriteLine(Is42((int)42L)); Console.WriteLine(Is42((int)43L)); } }"; var expectedOutput = @"True False True False True False True False"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact, WorkItem(17103, "https://github.com/dotnet/roslyn/issues/17103")] public void IsConstantPatternConversion_Negative() { var source = @"using System; public class Program { public static void Main() { byte b = 12; Console.WriteLine(b is 12L); Console.WriteLine(1 is null); } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (7,32): error CS0266: Cannot implicitly convert type 'long' to 'byte'. An explicit conversion exists (are you missing a cast?) // Console.WriteLine(b is 12L); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "12L").WithArguments("long", "byte").WithLocation(7, 32), // (8,32): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // Console.WriteLine(1 is null); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(8, 32) ); } [Fact] [WorkItem(9542, "https://github.com/dotnet/roslyn/issues/9542")] [WorkItem(16876, "https://github.com/dotnet/roslyn/issues/16876")] public void DecisionTreeCoverage_Positive() { // tests added to complete coverage of the decision tree and pattern-matching implementation var source = @"using System; public class X { public static void Main() { void M1(int i, bool b) { switch (i) { case 1 when b: Console.WriteLine(""M1a""); break; case 1: Console.WriteLine(""M1b""); break; case 2: Console.WriteLine(""M1c""); break; } } M1(1, true); M1(1, false); M1(2, false); M1(3, false); void M2(object o, bool b) { switch (o) { case null: Console.WriteLine(""M2a""); break; case var _ when b: Console.WriteLine(""M2b""); break; case 1: Console.WriteLine(""M2c""); break; } } M2(null, true); M2(1, true); M2(1, false); void M3(bool? b1, bool b2) { switch (b1) { case null: Console.WriteLine(""M3a""); break; case var _ when b2: Console.WriteLine(""M3b""); break; case true: Console.WriteLine(""M3c""); break; case false: Console.WriteLine(""M3d""); break; } } M3(null, true); M3(true, true); M3(true, false); M3(false, false); void M4(object o, bool b) { switch (o) { case var _ when b: Console.WriteLine(""M4a""); break; case int i: Console.WriteLine(""M4b""); break; } } M4(1, true); M4(1, false); void M5(int? i, bool b) { switch (i) { case var _ when b: Console.WriteLine(""M5a""); break; case null: Console.WriteLine(""M5b""); break; case int q: Console.WriteLine(""M5c""); break; } } M5(1, true); M5(null, false); M5(1, false); void M6(object o, bool b) { switch (o) { case var _ when b: Console.WriteLine(""M6a""); break; case object q: Console.WriteLine(""M6b""); break; case null: Console.WriteLine(""M6c""); break; } } M6(null, true); M6(1, false); M6(null, false); void M7(object o, bool b) { switch (o) { case null when b: Console.WriteLine(""M7a""); break; case object q: Console.WriteLine(""M7b""); break; case null: Console.WriteLine(""M7c""); break; } } M7(null, true); M7(1, false); M7(null, false); void M8(object o) { switch (o) { case null when false: throw null; case null: Console.WriteLine(""M8a""); break; } } M8(null); void M9(object o, bool b1, bool b2) { switch (o) { case var _ when b1: Console.WriteLine(""M9a""); break; case var _ when b2: Console.WriteLine(""M9b""); break; case var _: Console.WriteLine(""M9c""); break; } } M9(1, true, false); M9(1, false, true); M9(1, false, false); void M10(bool b) { const string nullString = null; switch (nullString) { case null when b: Console.WriteLine(""M10a""); break; case var _: Console.WriteLine(""M10b""); break; } } M10(true); M10(false); void M11() { const string s = """"; switch (s) { case string _: Console.WriteLine(""M11a""); break; } } M11(); void M12(bool cond) { const string s = """"; switch (s) { case string _ when cond: Console.WriteLine(""M12a""); break; case var _: Console.WriteLine(""M12b""); break; } } M12(true); M12(false); void M13(bool cond) { string s = """"; switch (s) { case string _ when cond: Console.WriteLine(""M13a""); break; case string _: Console.WriteLine(""M13b""); break; } } M13(true); M13(false); void M14() { const string s = """"; switch (s) { case s: Console.WriteLine(""M14a""); break; } } M14(); void M15() { const int i = 3; switch (i) { case 3: case 4: case 5: Console.WriteLine(""M15a""); break; } } M15(); } }"; var expectedOutput = @"M1a M1b M1c M2a M2b M2c M3a M3b M3c M3d M4a M4b M5a M5b M5c M6a M6b M6c M7a M7b M7c M8a M9a M9b M9c M10a M10b M11a M12a M12b M13a M13b M14a M15a "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] [WorkItem(9542, "https://github.com/dotnet/roslyn/issues/9542")] public void DecisionTreeCoverage_BadEquals() { // tests added to complete coverage of the decision tree and pattern-matching implementation var source = @"public class X { static void M1(float o) { switch (o) { case 0f/0f: break; } } } namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } } public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } } public struct Char { } public class String { } } namespace System { public struct Single { private Single m_value; public /*note bad return type*/ void Equals(Single other) { m_value = m_value + 1; } public /*note bad return type*/ void IsNaN(Single other) { } } } "; var compilation = CreateEmptyCompilation(source); compilation.VerifyDiagnostics( ); compilation.GetEmitDiagnostics().Where(d => d.Severity != DiagnosticSeverity.Warning).Verify( // (7,18): error CS0656: Missing compiler required member 'System.Single.IsNaN' // case 0f/0f: break; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "0f/0f").WithArguments("System.Single", "IsNaN").WithLocation(7, 18) ); } [Fact] [WorkItem(9542, "https://github.com/dotnet/roslyn/issues/9542")] public void DecisionTreeCoverage_DuplicateDefault() { // tests added to complete coverage of the decision tree and pattern-matching implementation var source = @"public class X { static void M1(object o) { switch (o) { case int x: default: default: break; } } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (9,13): error CS0152: The switch statement contains multiple cases with the label value 'default' // default: Diagnostic(ErrorCode.ERR_DuplicateCaseLabel, "default:").WithArguments("default").WithLocation(9, 13) ); } [Fact] [WorkItem(9542, "https://github.com/dotnet/roslyn/issues/9542")] public void DecisionTreeCoverage_Negative() { // tests added to complete coverage of the decision tree and pattern-matching implementation var source = @"public class X { static void M1(object o) { switch (o) { case 1: case int _: case 2: // subsumed break; } } static void M2(object o) { switch (o) { case 1: case int _: case int _: // subsumed break; } } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (9,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match. // case 2: // subsumed Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "2").WithLocation(9, 18), // (19,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match. // case int _: // subsumed Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "int _").WithLocation(19, 18) ); } [Fact] [WorkItem(17089, "https://github.com/dotnet/roslyn/issues/17089")] public void Dynamic_01() { var source = @"using System; public class X { static void M1(dynamic d) { if (d is 1) { Console.Write('r'); } else if (d is int i) { Console.Write('o'); } else if (d is var z) { long l = z; Console.Write('s'); } } static void M2(dynamic d) { switch (d) { case 1: Console.Write('l'); break; case int i: Console.Write('y'); break; case var z: long l = z; Console.Write('n'); break; } } public static void Main(string[] args) { M1(1); M1(2); M1(3L); M2(1); M2(2); M2(3L); } } "; var compilation = CreateCompilation(source, references: new MetadataReference[] { CSharpRef }, options: TestOptions.ReleaseExe); var comp = CompileAndVerify(compilation, expectedOutput: "roslyn"); } [Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")] public void OpenTypeMatch_01() { var source = @"using System; public class Base { } public class Derived : Base { } public class Program { public static void Main(string[] args) { M(new Derived()); M(new Base()); } public static void M<T>(T x) where T: Base { Console.Write(x is Derived b0); switch (x) { case Derived b1: Console.Write(1); break; default: Console.Write(0); break; } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7); compilation.VerifyDiagnostics( // (13,28): error CS8413: An expression of type 'T' cannot be handled by a pattern of type 'Derived' in C# 7.0. Please use language version 7.1 or greater. // Console.Write(x is Derived b0); Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "Derived").WithArguments("T", "Derived", "7.0", "7.1").WithLocation(13, 28), // (16,18): error CS8413: An expression of type 'T' cannot be handled by a pattern of type 'Derived' in C# 7.0. Please use language version 7.1 or greater. // case Derived b1: Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "Derived").WithArguments("T", "Derived", "7.0", "7.1").WithLocation(16, 18) ); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_1); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "True1False0"); } [Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")] public void OpenTypeMatch_02() { var source = @"using System; public class Base { } public class Derived : Base { } public class Program { public static void Main(string[] args) { M<Derived>(new Derived()); M<Derived>(new Base()); } public static void M<T>(Base x) { Console.Write(x is T b0); switch (x) { case T b1: Console.Write(1); break; default: Console.Write(0); break; } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7); compilation.VerifyDiagnostics( // (13,28): error CS8413: An expression of type 'Base' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater. // Console.Write(x is T b0); Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("Base", "T", "7.0", "7.1").WithLocation(13, 28), // (16,18): error CS8413: An expression of type 'Base' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater. // case T b1: Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("Base", "T", "7.0", "7.1") ); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_1); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "True1False0"); } [Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")] public void OpenTypeMatch_03() { var source = @"using System; public class Base { } public class Derived<T> : Base { } public class Program { public static void Main(string[] args) { M<Base>(new Derived<Base>()); M<Base>(new Base()); } public static void M<T>(T x) where T: Base { Console.Write(x is Derived<T> b0); switch (x) { case Derived<T> b1: Console.Write(1); break; default: Console.Write(0); break; } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7); compilation.VerifyDiagnostics( // (13,28): error CS8413: An expression of type 'T' cannot be handled by a pattern of type 'Derived<T>' in C# 7.0. Please use language version 7.1 or greater. // Console.Write(x is Derived<T> b0); Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "Derived<T>").WithArguments("T", "Derived<T>", "7.0", "7.1").WithLocation(13, 28), // (16,18): error CS8413: An expression of type 'T' cannot be handled by a pattern of type 'Derived<T>' in C# 7.0. Please use language version 7.1 or greater. // case Derived<T> b1: Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "Derived<T>").WithArguments("T", "Derived<T>", "7.0", "7.1").WithLocation(16, 18) ); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_1); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "True1False0"); } [Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")] public void OpenTypeMatch_04() { var source = @"using System; public class Base { } class Container<T> { public class Derived : Base { } } public class Program { public static void Main(string[] args) { M<Base>(new Container<Base>.Derived()); M<Base>(new Base()); } public static void M<T>(T x) where T: Base { Console.Write(x is Container<T>.Derived b0); switch (x) { case Container<T>.Derived b1: Console.Write(1); break; default: Console.Write(0); break; } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7); compilation.VerifyDiagnostics( // (16,28): error CS8413: An expression of type 'T' cannot be handled by a pattern of type 'Container<T>.Derived' in C# 7.0. Please use language version 7.1 or greater. // Console.Write(x is Container<T>.Derived b0); Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "Container<T>.Derived").WithArguments("T", "Container<T>.Derived", "7.0", "7.1").WithLocation(16, 28), // (19,18): error CS8413: An expression of type 'T' cannot be handled by a pattern of type 'Container<T>.Derived' in C# 7.0. Please use language version 7.1 or greater. // case Container<T>.Derived b1: Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "Container<T>.Derived").WithArguments("T", "Container<T>.Derived", "7.0", "7.1").WithLocation(19, 18) ); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_1); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "True1False0"); } [Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")] public void OpenTypeMatch_05() { var source = @"using System; public class Base { } class Container<T> { public class Derived : Base { } } public class Program { public static void Main(string[] args) { M<Base>(new Container<Base>.Derived[1]); M<Base>(new Base[1]); } public static void M<T>(T[] x) where T: Base { Console.Write(x is Container<T>.Derived[] b0); switch (x) { case Container<T>.Derived[] b1: Console.Write(1); break; default: Console.Write(0); break; } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7); compilation.VerifyDiagnostics( // (16,28): error CS8413: An expression of type 'T[]' cannot be handled by a pattern of type 'Container<T>.Derived[]' in C# 7.0. Please use language version 7.1 or greater. // Console.Write(x is Container<T>.Derived[] b0); Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "Container<T>.Derived[]").WithArguments("T[]", "Container<T>.Derived[]", "7.0", "7.1").WithLocation(16, 28), // (19,18): error CS8413: An expression of type 'T[]' cannot be handled by a pattern of type 'Container<T>.Derived[]' in C# 7.0. Please use language version 7.1 or greater. // case Container<T>.Derived[] b1: Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "Container<T>.Derived[]").WithArguments("T[]", "Container<T>.Derived[]", "7.0", "7.1").WithLocation(19, 18) ); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_1); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "True1False0"); } [Fact, WorkItem(19151, "https://github.com/dotnet/roslyn/issues/19151")] public void RefutablePatterns() { var source = @"public class Program { public static void Main(string[] args) { if (null as string is string) { } if (null as string is string s1) { } const string s = null; if (s is string) { } if (s is string s2) { } if (""goo"" is string s3) { } } void M1(int? i) { if (i is long) { } if (i is long l) { } switch (b) { case long m: break; } } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (8,13): warning CS0184: The given expression is never of the provided ('string') type // if (s is string) { } Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "s is string").WithArguments("string").WithLocation(8, 13), // (9,13): warning CS8416: The given expression never matches the provided pattern. // if (s is string s2) { } Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "s is string s2").WithLocation(9, 13), // (14,13): warning CS0184: The given expression is never of the provided ('long') type // if (i is long) { } Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "i is long").WithArguments("long").WithLocation(14, 13), // (15,18): error CS8121: An expression of type 'int?' cannot be handled by a pattern of type 'long'. // if (i is long l) { } Diagnostic(ErrorCode.ERR_PatternWrongType, "long").WithArguments("int?", "long").WithLocation(15, 18), // (16,17): error CS0103: The name 'b' does not exist in the current context // switch (b) { case long m: break; } Diagnostic(ErrorCode.ERR_NameNotInContext, "b").WithArguments("b").WithLocation(16, 17) ); } [Fact, WorkItem(19038, "https://github.com/dotnet/roslyn/issues/19038")] public void GenericDynamicIsObject() { var program = @" using System; public class Program { static void Main(string[] args) { M<dynamic>(new object()); M<dynamic>(null); M<dynamic>(""xyzzy""); } static void M<T>(object x) { switch (x) { case T t: Console.Write(""T""); break; case null: Console.Write(""n""); break; } } } "; var compilation = CreateCompilation(program, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"TnT"); } [Fact, WorkItem(19038, "https://github.com/dotnet/roslyn/issues/19038")] public void MatchNullableTypeParameter() { var program = @" using System; public class Program { static void Main(string[] args) { M<int>(1); M<int>(null); M<float>(3.14F); } static void M<T>(T? x) where T : struct { switch (x) { case T t: Console.Write(""T""); break; case null: Console.Write(""n""); break; } } } "; var compilation = CreateCompilation(program, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"TnT"); } [Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")] public void MatchRecursiveGenerics() { var program = @"using System; class Packet { } class Packet<U> : Packet { } public class C { static void Main() { Console.Write(M<Packet>(null)); Console.Write(M<Packet>(new Packet<Packet>())); Console.Write(M<Packet>(new Packet<int>())); Console.Write(M<Packet<int>>(new Packet<int>())); } static bool M<T>(T p) where T : Packet => p is Packet<T> p1; }"; CreateCompilation(program, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7).VerifyDiagnostics( // (12,52): error CS8314: An expression of type 'T' cannot be handled by a pattern of type 'Packet<T>' in C# 7.0. Please use language version 7.1 or greater. // static bool M<T>(T p) where T : Packet => p is Packet<T> p1; Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "Packet<T>").WithArguments("T", "Packet<T>", "7.0", "7.1").WithLocation(12, 52) ); var compilation = CreateCompilation(program, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_1); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"FalseTrueFalseFalse"); } [Fact, WorkItem(19038, "https://github.com/dotnet/roslyn/issues/19038")] public void MatchRestrictedTypes_Fail() { var program = @"using System; unsafe public class C { static bool M(TypedReference x, int* p, ref int z) { var n1 = x is TypedReference x0; // ok var p1 = p is int* p0; // syntax error 1 var r1 = z is ref int z0; // syntax error 2 var b1 = x is object o1; // not allowed 1 var b2 = p is object o2; // not allowed 2 var b3 = z is object o3; // ok return b1 && b2 && b3; } }"; var compilation = CreateCompilation(program, options: TestOptions.DebugDll.WithAllowUnsafe(true)); compilation.VerifyDiagnostics( // (6,23): error CS1525: Invalid expression term 'int' // var p1 = p is int* p0; // syntax error 1 Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(6, 23), // (7,23): error CS1525: Invalid expression term 'ref' // var r1 = z is ref int z0; // syntax error 2 Diagnostic(ErrorCode.ERR_InvalidExprTerm, "ref int").WithArguments("ref").WithLocation(7, 23), // (7,27): error CS1525: Invalid expression term 'int' // var r1 = z is ref int z0; // syntax error 2 Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(7, 27), // (7,31): error CS1002: ; expected // var r1 = z is ref int z0; // syntax error 2 Diagnostic(ErrorCode.ERR_SemicolonExpected, "z0").WithLocation(7, 31), // (6,28): error CS0103: The name 'p0' does not exist in the current context // var p1 = p is int* p0; // syntax error 1 Diagnostic(ErrorCode.ERR_NameNotInContext, "p0").WithArguments("p0").WithLocation(6, 28), // (7,23): error CS1073: Unexpected token 'ref' // var r1 = z is ref int z0; // syntax error 2 Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(7, 23), // (7,31): error CS0103: The name 'z0' does not exist in the current context // var r1 = z is ref int z0; // syntax error 2 Diagnostic(ErrorCode.ERR_NameNotInContext, "z0").WithArguments("z0").WithLocation(7, 31), // (7,31): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // var r1 = z is ref int z0; // syntax error 2 Diagnostic(ErrorCode.ERR_IllegalStatement, "z0").WithLocation(7, 31), // (9,23): error CS8121: An expression of type 'TypedReference' cannot be handled by a pattern of type 'object'. // var b1 = x is object o1; // not allowed 1 Diagnostic(ErrorCode.ERR_PatternWrongType, "object").WithArguments("System.TypedReference", "object").WithLocation(9, 23), // (10,23): error CS8521: Pattern-matching is not permitted for pointer types. // var b2 = p is object o2; // not allowed 2 Diagnostic(ErrorCode.ERR_PointerTypeInPatternMatching, "object").WithLocation(10, 23) ); } [Fact, WorkItem(19038, "https://github.com/dotnet/roslyn/issues/19038")] public void MatchRestrictedTypes_Success() { var program = @"using System; using System.Reflection; unsafe public class C { public int Value; static void Main() { C a = new C { Value = 12 }; FieldInfo info = typeof(C).GetField(""Value""); TypedReference reference = __makeref(a); if (!(reference is TypedReference reference0)) throw new Exception(""TypedReference""); info.SetValueDirect(reference0, 34); if (a.Value != 34) throw new Exception(""SetValueDirect""); int z = 56; if (CopyRefInt(ref z) != 56) throw new Exception(""ref z""); Console.WriteLine(""ok""); } static int CopyRefInt(ref int z) { if (!(z is int z0)) throw new Exception(""CopyRefInt""); return z0; } }"; var compilation = CreateCompilation(program, options: TestOptions.DebugExe.WithAllowUnsafe(true)); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: "ok"); } [Fact] [WorkItem(406203, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=406203")] [WorkItem(406205, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=406205")] public void DoubleEvaluation() { var source = @"using System; public class X { public static void Main(string[] args) { { int? a = 0; if (a++ is int b) { Console.WriteLine(b); } Console.WriteLine(a); } { int? a = 0; if (++a is int b) { Console.WriteLine(b); } Console.WriteLine(a); } { if (Func() is int b) { Console.WriteLine(b); } } } public static int? Func() { Console.WriteLine(""Func called""); return 2; } } "; var expectedOutput = @"0 1 1 1 Func called 2"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: expectedOutput); compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void TestVoidInIsOrAs_01() { // though silly, it is not forbidden to test a void value's type var source = @"using System; class Program { static void Main() { if (Console.Write(""Hello"") is object) {} } } "; var expectedOutput = @"Hello"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (6,13): warning CS0184: The given expression is never of the provided ('object') type // if (Console.Write("Hello") is object) {} Diagnostic(ErrorCode.WRN_IsAlwaysFalse, @"Console.Write(""Hello"") is object").WithArguments("object").WithLocation(6, 13) ); CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void TestVoidInIsOrAs_02() { var source = @"using System; class Program { static void Main() { var o = Console.WriteLine(""world!"") as object; if (o != null) throw null; } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (6,17): error CS0039: Cannot convert type 'void' to 'object' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion // var o = Console.WriteLine("world!") as object; Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, @"Console.WriteLine(""world!"") as object").WithArguments("void", "object").WithLocation(6, 17) ); } [Fact] public void TestVoidInIsOrAs_03() { var source = @"using System; class Program { static void Main() { M<object>(); } static void M<T>() where T : class { var o = Console.WriteLine(""Hello"") as T; if (o != null) throw null; } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (10,17): error CS0039: Cannot convert type 'void' to 'T' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion // var o = Console.WriteLine("Hello") as T; Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, @"Console.WriteLine(""Hello"") as T").WithArguments("void", "T").WithLocation(10, 17) ); } [Fact] public void TestVoidInIsOrAs_04() { var source = @"using System; class Program { static void Main() { if (Console.WriteLine(""Hello"") is var x) { } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (6,13): error CS8117: Invalid operand for pattern match; value required, but found 'void'. // if (Console.WriteLine("Hello") is var x) { } Diagnostic(ErrorCode.ERR_BadPatternExpression, @"Console.WriteLine(""Hello"")").WithArguments("void").WithLocation(6, 13) ); } [Fact] public void TestVoidInIsOrAs_05() { var source = @"using System; class Program { static void Main() { if (Console.WriteLine(""Hello"") is var _) {} } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (6,13): error CS8117: Invalid operand for pattern match; value required, but found 'void'. // if (Console.WriteLine("Hello") is var _) {} Diagnostic(ErrorCode.ERR_BadPatternExpression, @"Console.WriteLine(""Hello"")").WithArguments("void").WithLocation(6, 13) ); } [Fact] public void TestVoidInSwitch() { var source = @"using System; class Program { static void Main() { switch (Console.WriteLine(""Hello"")) { default: break; } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (6,17): error CS8119: The switch expression must be a value; found 'void'. // switch (Console.WriteLine("Hello")) Diagnostic(ErrorCode.ERR_SwitchExpressionValueExpected, @"Console.WriteLine(""Hello"")").WithArguments("void").WithLocation(6, 17) ); } [Fact, WorkItem(20103, "https://github.com/dotnet/roslyn/issues/20103")] public void TestNullInIsPattern() { var source = @"using System; class Program { static void Main() { const string s = null; if (s is string) {} else { Console.Write(""Hello ""); } if (s is string t) {} else { Console.WriteLine(""World""); } } } "; var expectedOutput = @"Hello World"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (7,13): warning CS0184: The given expression is never of the provided ('string') type // if (s is string) {} else { Console.Write("Hello "); } Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "s is string").WithArguments("string").WithLocation(7, 13), // (8,13): warning CS8416: The given expression never matches the provided pattern. // if (s is string t) {} else { Console.WriteLine("World"); } Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "s is string t").WithLocation(8, 13) ); CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact, WorkItem(22619, "https://github.com/dotnet/roslyn/issues/22619")] public void MissingSideEffect() { var source = @"using System; internal class Program { private static void Main() { try { var test = new Program(); var result = test.IsVarMethod(); Console.WriteLine($""Result = {result}""); Console.Read(); } catch (Exception) { Console.WriteLine(""Exception""); } } private int IsVarMethod() => ThrowingMethod() is var _ ? 1 : 0; private bool ThrowingMethod() => throw new Exception(""Oh""); } "; var expectedOutput = @"Exception"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void TestArrayOfPointer() { var source = @"using System; class Program { unsafe static void Main() { object o = new byte*[10]; Console.WriteLine(o is byte*[]); // True Console.WriteLine(o is byte*[] _); // True Console.WriteLine(o is byte*[] x1); // True Console.WriteLine(o is byte**[]); // False Console.WriteLine(o is byte**[] _); // False Console.WriteLine(o is byte**[] x2); // False o = new byte**[10]; Console.WriteLine(o is byte**[]); // True Console.WriteLine(o is byte**[] _); // True Console.WriteLine(o is byte**[] x3); // True Console.WriteLine(o is byte*[]); // False Console.WriteLine(o is byte*[] _); // False Console.WriteLine(o is byte*[] x4); // False } } "; var expectedOutput = @"True True True False False False True True True False False False"; var compilation = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: expectedOutput, verify: Verification.Fails); } [Fact] public void DefaultPattern() { var source = @"class Program { public static void Main() { int i = 12; if (i is default) {} // error 1 if (i is (default)) {} // error 2 if (i is (((default)))) {} // error 3 switch (i) { case default: break; } // error 4 switch (i) { case (default): break; } // error 5 switch (i) { case default when true: break; } // error 6 switch (i) { case (default) when true: break; } // error 7 } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (6,18): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (i is default) {} // error 1 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(6, 18), // (7,19): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (i is (default)) {} // error 2 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(7, 19), // (8,21): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (i is (((default)))) {} // error 3 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(8, 21), // (9,27): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // switch (i) { case default: break; } // error 4 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(9, 27), // (10,28): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // switch (i) { case (default): break; } // error 5 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(10, 28), // (11,27): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // switch (i) { case default when true: break; } // error 6 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(11, 27), // (12,28): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // switch (i) { case (default) when true: break; } // error 7 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(12, 28) ); var tree = compilation.SyntaxTrees.Single(); var caseDefault = tree.GetRoot().DescendantNodes().OfType<CasePatternSwitchLabelSyntax>().First(); var model = compilation.GetSemanticModel(tree, ignoreAccessibility: false); Assert.Equal("System.Int32", model.GetTypeInfo(caseDefault.Pattern).Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetTypeInfo(caseDefault.Pattern).ConvertedType.ToTestDisplayString()); Assert.False(model.GetConstantValue(caseDefault.Pattern).HasValue); } [Fact] public void EventInitializers_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static event System.Func<bool> Test1 = GetDelegate(1 is int x1 && Dummy(x1)); static System.Func<bool> GetDelegate(bool value) => () => value; static bool Dummy(int x) { System.Console.WriteLine(x); return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 True"); CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (9,65): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater. // static event System.Func<bool> Test1 = GetDelegate(1 is int x1 && Dummy(x1)); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(9, 65) ); } [Fact] public void ExhaustiveBoolSwitch00() { // Note that the switches in this code are exhaustive. The idea of a switch // being exhaustive is new with the addition of pattern-matching; this code // used to give errors that are no longer applicable due to the spec change. var source = @" using System; public class C { public static void Main() { M(true); M(false); Console.WriteLine(M2(true)); Console.WriteLine(M2(false)); } public static void M(bool e) { bool b; switch (e) { case true: b = true; break; case false: b = false; break; } Console.WriteLine(b); // no more error CS0165: Use of unassigned local variable 'b' } public static bool M2(bool e) // no more error CS0161: not all code paths return a value { switch (e) { case true: return true; case false: return false; } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"True False True False"); } [Fact, WorkItem(24865, "https://github.com/dotnet/roslyn/issues/24865")] public void ExhaustiveBoolSwitch01() { var source = @" using System; public class C { public static void Main() { M(true); M(false); Console.WriteLine(M2(true)); Console.WriteLine(M2(false)); } public static void M(bool e) { bool b; switch (e) { case true when true: b = true; break; case false: b = false; break; } Console.WriteLine(b); } public static bool M2(bool e) { switch (e) { case true when true: return true; case false: return false; } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"True False True False"); } [Fact] [WorkItem(27218, "https://github.com/dotnet/roslyn/issues/27218")] public void IsPatternMatchingDoesNotCopyEscapeScopes_01() { CreateCompilationWithMscorlibAndSpan(@" using System; public class C { public ref int M() { Span<int> outer = stackalloc int[100]; if (outer is Span<int> inner) { return ref inner[5]; } throw null; } }").VerifyDiagnostics( // (10,24): error CS8352: Cannot use local 'inner' in this context because it may expose referenced variables outside of their declaration scope // return ref inner[5]; Diagnostic(ErrorCode.ERR_EscapeLocal, "inner").WithArguments("inner").WithLocation(10, 24)); } [Fact] [WorkItem(27218, "https://github.com/dotnet/roslyn/issues/27218")] public void IsPatternMatchingDoesNotCopyEscapeScopes_03() { CreateCompilationWithMscorlibAndSpan(parseOptions: TestOptions.RegularWithPatternCombinators, text: @" using System; public class C { public ref int M() { Span<int> outer = stackalloc int[100]; if (outer is ({} and var x) and Span<int> inner) { return ref inner[5]; } throw null; } }").VerifyDiagnostics( // (8,13): warning CS8794: An expression of type 'Span<int>' always matches the provided pattern. // if (outer is ({} and var x) and Span<int> inner) Diagnostic(ErrorCode.WRN_IsPatternAlways, "outer is ({} and var x) and Span<int> inner").WithArguments("System.Span<int>").WithLocation(8, 13), // (10,24): error CS8352: Cannot use local 'inner' in this context because it may expose referenced variables outside of their declaration scope // return ref inner[5]; Diagnostic(ErrorCode.ERR_EscapeLocal, "inner").WithArguments("inner").WithLocation(10, 24) ); } [Fact] [WorkItem(27218, "https://github.com/dotnet/roslyn/issues/27218")] public void CasePatternMatchingDoesNotCopyEscapeScopes_01() { CreateCompilationWithMscorlibAndSpan(@" using System; public class C { public ref int M() { Span<int> outer = stackalloc int[100]; switch (outer) { case Span<int> inner: { return ref inner[5]; } } throw null; } }").VerifyDiagnostics( // (12,28): error CS8352: Cannot use local 'inner' in this context because it may expose referenced variables outside of their declaration scope // return ref inner[5]; Diagnostic(ErrorCode.ERR_EscapeLocal, "inner").WithArguments("inner").WithLocation(12, 28)); } [Fact] [WorkItem(27218, "https://github.com/dotnet/roslyn/issues/27218")] public void CasePatternMatchingDoesNotCopyEscapeScopes_03() { CreateCompilationWithMscorlibAndSpan(parseOptions: TestOptions.RegularWithPatternCombinators, text: @" using System; public class C { public ref int M() { Span<int> outer = stackalloc int[100]; switch (outer) { case {} and Span<int> inner: { return ref inner[5]; } } throw null; } }").VerifyDiagnostics( // (12,28): error CS8352: Cannot use local 'inner' in this context because it may expose referenced variables outside of their declaration scope // return ref inner[5]; Diagnostic(ErrorCode.ERR_EscapeLocal, "inner").WithArguments("inner").WithLocation(12, 28)); } [Fact] [WorkItem(28633, "https://github.com/dotnet/roslyn/issues/28633")] public void CasePatternMatchingDoesNotCopyEscapeScopes_02() { CreateCompilationWithMscorlibAndSpan(parseOptions: TestOptions.RegularWithRecursivePatterns, text: @" using System; public ref struct R { public R Prop => this; public void Deconstruct(out R X, out R Y) => X = Y = this; public static implicit operator R(Span<int> span) => new R(); } public class C { public R M1() { R outer = stackalloc int[100]; switch (outer) { case { Prop: var x }: return x; // error 1 } } public R M2() { R outer = stackalloc int[100]; switch (outer) { case { Prop: R x }: return x; // error 2 } } public R M3() { R outer = stackalloc int[100]; switch (outer) { case (var x, var y): return x; // error 3 } } public R M4() { R outer = stackalloc int[100]; switch (outer) { case (R x, R y): return x; // error 4 } } public R M5() { R outer = stackalloc int[100]; switch (outer) { case var (x, y): return x; // error 5 } } public R M6() { R outer = stackalloc int[100]; switch (outer) { case { } x: return x; // error 6 } } public R M7() { R outer = stackalloc int[100]; switch (outer) { case (_, _) x: return x; // error 7 } } } ").VerifyDiagnostics( // (16,42): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // case { Prop: var x }: return x; // error 1 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(16, 42), // (24,40): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // case { Prop: R x }: return x; // error 2 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(24, 40), // (32,41): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // case (var x, var y): return x; // error 3 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(32, 41), // (40,37): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // case (R x, R y): return x; // error 4 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(40, 37), // (48,37): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // case var (x, y): return x; // error 5 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(48, 37), // (56,32): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // case { } x: return x; // error 6 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(56, 32), // (64,35): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // case (_, _) x: return x; // error 7 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(64, 35) ); } [Fact] [WorkItem(28633, "https://github.com/dotnet/roslyn/issues/28633")] public void CasePatternMatchingDoesNotCopyEscapeScopes_04() { CreateCompilationWithMscorlibAndSpan(parseOptions: TestOptions.RegularWithPatternCombinators, text: @" using System; public ref struct R { public R Prop => this; public void Deconstruct(out R X, out R Y) => X = Y = this; public static implicit operator R(Span<int> span) => new R(); } public class C { public R M1() { R outer = stackalloc int[100]; switch (outer) { case var _ and {} and { Prop: var _ and {} and var x }: return x; // error 1 } } public R M2() { R outer = stackalloc int[100]; switch (outer) { case var _ and {} and { Prop: var _ and {} and R x }: return x; // error 2 } } public R M3() { R outer = stackalloc int[100]; switch (outer) { case var _ and {} and (var _ and {} and var x, var _ and {} and var y): return x; // error 3 } } public R M4() { R outer = stackalloc int[100]; switch (outer) { case var _ and {} and (var _ and {} and R x, var _ and {} and R y): return x; // error 4 } } public R M5() { R outer = stackalloc int[100]; switch (outer) { case var _ and {} and var (x, y): return x; // error 5 } } public R M6() { R outer = stackalloc int[100]; switch (outer) { case var _ and {} and { } x: return x; // error 6 } } public R M7() { R outer = stackalloc int[100]; switch (outer) { case var _ and {} and (var _ and {} and _, var _ and {} and _) x: return x; // error 7 } } } ").VerifyDiagnostics( // (16,76): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // case var _ and {} and { Prop: var _ and {} and var x }: return x; // error 1 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(16, 76), // (24,74): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // case var _ and {} and { Prop: var _ and {} and R x }: return x; // error 2 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(24, 74), // (32,92): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // case var _ and {} and (var _ and {} and var x, var _ and {} and var y): return x; // error 3 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(32, 92), // (40,88): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // case var _ and {} and (var _ and {} and R x, var _ and {} and R y): return x; // error 4 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(40, 88), // (48,54): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // case var _ and {} and var (x, y): return x; // error 5 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(48, 54), // (56,49): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // case var _ and {} and { } x: return x; // error 6 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(56, 49), // (64,86): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // case var _ and {} and (var _ and {} and _, var _ and {} and _) x: return x; // error 7 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(64, 86) ); } [Fact] [WorkItem(28633, "https://github.com/dotnet/roslyn/issues/28633")] public void IsPatternMatchingDoesNotCopyEscapeScopes_02() { CreateCompilationWithMscorlibAndSpan(parseOptions: TestOptions.RegularWithRecursivePatterns, text: @" using System; public ref struct R { public R Prop => this; public void Deconstruct(out R X, out R Y) => X = Y = this; public static implicit operator R(Span<int> span) => new R(); } public class C { public R M1() { R outer = stackalloc int[100]; if (outer is { Prop: var x }) return x; // error 1 throw null; } public R M2() { R outer = stackalloc int[100]; if (outer is { Prop: R x }) return x; // error 2 throw null; } public R M3() { R outer = stackalloc int[100]; if (outer is (var x, var y)) return x; // error 3 throw null; } public R M4() { R outer = stackalloc int[100]; if (outer is (R x, R y)) return x; // error 4 throw null; } public R M5() { R outer = stackalloc int[100]; if (outer is var (x, y)) return x; // error 5 throw null; } public R M6() { R outer = stackalloc int[100]; if (outer is { } x) return x; // error 6 throw null; } public R M7() { R outer = stackalloc int[100]; if (outer is (_, _) x) return x; // error 7 throw null; } } ").VerifyDiagnostics( // (14,46): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // if (outer is { Prop: var x }) return x; // error 1 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(14, 46), // (20,44): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // if (outer is { Prop: R x }) return x; // error 2 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(20, 44), // (26,45): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // if (outer is (var x, var y)) return x; // error 3 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(26, 45), // (32,41): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // if (outer is (R x, R y)) return x; // error 4 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(32, 41), // (38,41): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // if (outer is var (x, y)) return x; // error 5 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(38, 41), // (44,36): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // if (outer is { } x) return x; // error 6 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(44, 36), // (50,39): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // if (outer is (_, _) x) return x; // error 7 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(50, 39) ); } [Fact] [WorkItem(28633, "https://github.com/dotnet/roslyn/issues/28633")] public void IsPatternMatchingDoesNotCopyEscapeScopes_04() { CreateCompilationWithMscorlibAndSpan(parseOptions: TestOptions.RegularWithPatternCombinators, text: @" using System; public ref struct R { public R Prop => this; public void Deconstruct(out R X, out R Y) => X = Y = this; public static implicit operator R(Span<int> span) => new R(); } public class C { public R M1() { R outer = stackalloc int[100]; if (outer is var _ and {} and { Prop: var _ and {} and var x }) return x; // error 1 throw null; } public R M2() { R outer = stackalloc int[100]; if (outer is var _ and {} and { Prop: var _ and {} and R x }) return x; // error 2 throw null; } public R M3() { R outer = stackalloc int[100]; if (outer is var _ and {} and (var _ and {} and var x, var _ and {} and var y)) return x; // error 3 throw null; } public R M4() { R outer = stackalloc int[100]; if (outer is var _ and {} and (var _ and {} and R x, var _ and {} and R y)) return x; // error 4 throw null; } public R M5() { R outer = stackalloc int[100]; if (outer is var _ and {} and var (x, y)) return x; // error 5 throw null; } public R M6() { R outer = stackalloc int[100]; if (outer is var _ and {} and { } x) return x; // error 6 throw null; } public R M7() { R outer = stackalloc int[100]; if (outer is var _ and {} and (_, _) x) return x; // error 7 throw null; } } ").VerifyDiagnostics( // if (outer is var _ and {} and { Prop: var _ and {} and var x }) return x; // error 1 Diagnostic(ErrorCode.WRN_IsPatternAlways, "outer is var _ and {} and { Prop: var _ and {} and var x }").WithArguments("R").WithLocation(14, 13), // (14,80): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // if (outer is var _ and {} and { Prop: var _ and {} and var x }) return x; // error 1 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(14, 80), // (20,13): warning CS8794: An expression of type 'R' always matches the provided pattern. // if (outer is var _ and {} and { Prop: var _ and {} and R x }) return x; // error 2 Diagnostic(ErrorCode.WRN_IsPatternAlways, "outer is var _ and {} and { Prop: var _ and {} and R x }").WithArguments("R").WithLocation(20, 13), // (20,78): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // if (outer is var _ and {} and { Prop: var _ and {} and R x }) return x; // error 2 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(20, 78), // (26,13): warning CS8794: An expression of type 'R' always matches the provided pattern. // if (outer is var _ and {} and (var _ and {} and var x, var _ and {} and var y)) return x; // error 3 Diagnostic(ErrorCode.WRN_IsPatternAlways, "outer is var _ and {} and (var _ and {} and var x, var _ and {} and var y)").WithArguments("R").WithLocation(26, 13), // (26,96): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // if (outer is var _ and {} and (var _ and {} and var x, var _ and {} and var y)) return x; // error 3 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(26, 96), // (32,13): warning CS8794: An expression of type 'R' always matches the provided pattern. // if (outer is var _ and {} and (var _ and {} and R x, var _ and {} and R y)) return x; // error 4 Diagnostic(ErrorCode.WRN_IsPatternAlways, "outer is var _ and {} and (var _ and {} and R x, var _ and {} and R y)").WithArguments("R").WithLocation(32, 13), // (32,92): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // if (outer is var _ and {} and (var _ and {} and R x, var _ and {} and R y)) return x; // error 4 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(32, 92), // (38,13): warning CS8794: An expression of type 'R' always matches the provided pattern. // if (outer is var _ and {} and var (x, y)) return x; // error 5 Diagnostic(ErrorCode.WRN_IsPatternAlways, "outer is var _ and {} and var (x, y)").WithArguments("R").WithLocation(38, 13), // (38,58): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // if (outer is var _ and {} and var (x, y)) return x; // error 5 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(38, 58), // (44,13): warning CS8794: An expression of type 'R' always matches the provided pattern. // if (outer is var _ and {} and { } x) return x; // error 6 Diagnostic(ErrorCode.WRN_IsPatternAlways, "outer is var _ and {} and { } x").WithArguments("R").WithLocation(44, 13), // (44,53): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // if (outer is var _ and {} and { } x) return x; // error 6 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(44, 53), // (50,13): warning CS8794: An expression of type 'R' always matches the provided pattern. // if (outer is var _ and {} and (_, _) x) return x; // error 7 Diagnostic(ErrorCode.WRN_IsPatternAlways, "outer is var _ and {} and (_, _) x").WithArguments("R").WithLocation(50, 13), // (50,56): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // if (outer is var _ and {} and (_, _) x) return x; // error 7 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(50, 56) ); } [Fact] [WorkItem(28633, "https://github.com/dotnet/roslyn/issues/28633")] public void EscapeScopeInSubpatternOfNonRefType() { CreateCompilationWithMscorlibAndSpan(parseOptions: TestOptions.RegularWithRecursivePatterns, text: @" using System; public ref struct R { public R RProp => this; public S SProp => new S(); public void Deconstruct(out S X, out S Y) => X = Y = new S(); public static implicit operator R(Span<int> span) => new R(); } public struct S { public R RProp => new R(); } public class C { public R M1() { R outer = stackalloc int[100]; if (outer is { SProp: { RProp: var x }}) return x; // OK throw null; } public R M2() { R outer = stackalloc int[100]; switch (outer) { case { SProp: { RProp: var x }}: return x; // OK } } public R M3() { R outer = stackalloc int[100]; if (outer is ({ RProp: var x }, _)) return x; // OK throw null; } public R M4() { R outer = stackalloc int[100]; switch (outer) { case ({ RProp: var x }, _): return x; // OK } } } ").VerifyDiagnostics( ); } [Fact] [WorkItem(39960, "https://github.com/dotnet/roslyn/issues/39960")] public void MissingExceptionType() { var source = @" class C { void M(bool b, dynamic d) { _ = b ? throw new System.NullReferenceException() : throw null; L(); throw null; void L() => throw d; } } "; var comp = CreateCompilation(source); comp.MakeTypeMissing(WellKnownType.System_Exception); comp.VerifyDiagnostics( // (7,21): error CS0518: Predefined type 'System.Exception' is not defined or imported // ? throw new System.NullReferenceException() Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "new System.NullReferenceException()").WithArguments("System.Exception").WithLocation(7, 21), // (8,21): error CS0518: Predefined type 'System.Exception' is not defined or imported // : throw null; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "null").WithArguments("System.Exception").WithLocation(8, 21), // (10,15): error CS0518: Predefined type 'System.Exception' is not defined or imported // throw null; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "null").WithArguments("System.Exception").WithLocation(10, 15), // (11,27): error CS0518: Predefined type 'System.Exception' is not defined or imported // void L() => throw d; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "d").WithArguments("System.Exception").WithLocation(11, 27) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.MakeTypeMissing(WellKnownType.System_Exception); comp.VerifyDiagnostics( // (7,21): error CS0155: The type caught or thrown must be derived from System.Exception // ? throw new System.NullReferenceException() Diagnostic(ErrorCode.ERR_BadExceptionType, "new System.NullReferenceException()").WithLocation(7, 21), // (11,27): error CS0155: The type caught or thrown must be derived from System.Exception // void L() => throw d; Diagnostic(ErrorCode.ERR_BadExceptionType, "d").WithLocation(11, 27) ); } [Fact] public void MissingExceptionType_In7() { var source = @" class C { static void Main() { try { Test(); } catch { System.Console.WriteLine(""in catch""); } } static void Test() { throw null; } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7); comp.MakeTypeMissing(WellKnownType.System_Exception); comp.VerifyDiagnostics( ); CompileAndVerify(comp, expectedOutput: "in catch"); } [Fact, WorkItem(50301, "https://github.com/dotnet/roslyn/issues/50301")] public void SymbolsForSwitchExpressionLocals() { var source = @" class C { static string M(object o) { return o switch { int i => $""Number: {i}"", _ => ""Don't know"" }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); comp.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M"" parameterNames=""o""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""9"" endLine=""10"" endColumn=""11"" document=""1"" /> <entry offset=""0xf"" startLine=""8"" startColumn=""22"" endLine=""8"" endColumn=""36"" document=""1"" /> <entry offset=""0x22"" startLine=""9"" startColumn=""18"" endLine=""9"" endColumn=""30"" document=""1"" /> <entry offset=""0x28"" hidden=""true"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2a""> <scope startOffset=""0xf"" endOffset=""0x22""> <local name=""i"" il_index=""0"" il_start=""0xf"" il_end=""0x22"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols> "); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.Patterns)] public class PatternMatchingTests : PatternMatchingTestBase { [Fact] public void DemoModes() { var source = @" public class Vec { public static void Main() { object o = ""Pass""; int i1 = 0b001010; // binary literals int i2 = 23_554; // digit separators // local functions // Note: due to complexity and cost of parsing local functions we // don't try to parse if the feature isn't enabled int f() => 2; ref int i3 = ref i1; // ref locals string s = o is string k ? k : null; // pattern matching //let var i4 = 3; // let //int i5 = o match (case * : 7); // match //object q = (o is null) ? o : throw null; // throw expressions //if (q is Vec(3)) {} // recursive pattern } public int X => 4; public Vec(int x) {} } "; CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular6).VerifyDiagnostics( // (7,18): error CS8059: Feature 'binary literals' is not available in C# 6. Please use language version 7.0 or greater. // int i1 = 0b001010; // binary literals Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "").WithArguments("binary literals", "7.0").WithLocation(7, 18), // (8,18): error CS8059: Feature 'digit separators' is not available in C# 6. Please use language version 7.0 or greater. // int i2 = 23_554; // digit separators Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "").WithArguments("digit separators", "7.0").WithLocation(8, 18), // (12,13): error CS8059: Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater. // int f() => 2; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "f").WithArguments("local functions", "7.0").WithLocation(12, 13), // (13,9): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref int i3 = ref i1; // ref locals Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(13, 9), // (13,22): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7.0 or greater. // ref int i3 = ref i1; // ref locals Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7.0").WithLocation(13, 22), // (14,20): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // string s = o is string k ? k : null; // pattern matching Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "o is string k").WithArguments("pattern matching", "7.0").WithLocation(14, 20), // (12,13): warning CS8321: The local function 'f' is declared but never used // int f() => 2; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(12, 13) ); // enables binary literals, digit separators, local functions, ref locals, pattern matching CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics( // (8,13): warning CS0219: The variable 'i2' is assigned but its value is never used // int i2 = 23_554; // digit separators Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i2").WithArguments("i2").WithLocation(8, 13), // (12,13): warning CS8321: The local function 'f' is declared but never used // int f() => 2; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "f").WithArguments("f").WithLocation(12, 13) ); } [Fact] public void SimplePatternTest() { var source = @"using System; public class X { public static void Main() { var s = nameof(Main); if (s is string t) Console.WriteLine(""1. {0}"", t); s = null; Console.WriteLine(""2. {0}"", s is string w ? w : nameof(X)); int? x = 12; {if (x is var y) Console.WriteLine(""3. {0}"", y);} {if (x is int y) Console.WriteLine(""4. {0}"", y);} x = null; {if (x is var y) Console.WriteLine(""5. {0}"", y);} {if (x is int y) Console.WriteLine(""6. {0}"", y);} Console.WriteLine(""7. {0}"", (x is bool is bool)); } }"; var expectedOutput = @"1. Main 2. X 3. 12 4. 12 5. 7. True"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // warning CS0184: The given expression is never of the provided ('bool') type // Console.WriteLine("7. {0}", (x is bool is bool)); Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "x is bool").WithArguments("bool"), // warning CS0183: The given expression is always of the provided ('bool') type // Console.WriteLine("7. {0}", (x is bool is bool)); Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "x is bool is bool").WithArguments("bool") ); var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void NullablePatternTest() { var source = @"using System; public class X { public static void Main() { T(null); T(1); } public static void T(object x) { if (x is Nullable<int> y) Console.WriteLine($""expression {x} is Nullable<int> y""); } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (11,18): error CS8116: It is not legal to use nullable type 'int?' in a pattern; use the underlying type 'int' instead. // if (x is Nullable<int> y) Console.WriteLine($"expression {x} is Nullable<int> y"); Diagnostic(ErrorCode.ERR_PatternNullableType, "Nullable<int>").WithArguments("int").WithLocation(11, 18) ); } [Fact] public void UnconstrainedPatternTest() { var source = @"using System; public class X { public static void Main() { Test<string>(1); Test<int>(""goo""); Test<int>(1); Test<int>(1.2); Test<double>(1.2); Test<int?>(1); Test<int?>(null); Test<string>(null); } public static void Test<T>(object x) { if (x is T y) Console.WriteLine($""expression {x} is {typeof(T).Name} {y}""); else Console.WriteLine($""expression {x} is not {typeof(T).Name}""); } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); using (new EnsureInvariantCulture()) { var expectedOutput = @"expression 1 is not String expression goo is not Int32 expression 1 is Int32 1 expression 1.2 is not Int32 expression 1.2 is Double 1.2 expression 1 is Nullable`1 1 expression is not Nullable`1 expression is not String"; var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } } [Fact, WorkItem(10932, "https://github.com/dotnet/roslyn/issues/10932")] public void PatternErrors() { var source = @"using System; using NullableInt = System.Nullable<int>; public class X { public static void Main() { var s = nameof(Main); byte b = 1; if (s is string t) { } else Console.WriteLine(t); if (null is dynamic t2) { } // null not allowed if (s is NullableInt x) { } // error: cannot use nullable type if (s is long l) { } // error: cannot convert string to long if (b is 1000) { } // error: cannot convert 1000 to byte } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (10,13): error CS8117: Invalid operand for pattern match; value required, but found '<null>'. // if (null is dynamic t2) { } // null not allowed Diagnostic(ErrorCode.ERR_BadPatternExpression, "null").WithArguments("<null>").WithLocation(10, 13), // (11,18): error CS8116: It is not legal to use nullable type 'int?' in a pattern; use the underlying type 'int' instead. // if (s is NullableInt x) { } // error: cannot use nullable type Diagnostic(ErrorCode.ERR_PatternNullableType, "NullableInt").WithArguments("int").WithLocation(11, 18), // (12,18): error CS8121: An expression of type 'string' cannot be handled by a pattern of type 'long'. // if (s is long l) { } // error: cannot convert string to long Diagnostic(ErrorCode.ERR_PatternWrongType, "long").WithArguments("string", "long").WithLocation(12, 18), // (13,18): error CS0031: Constant value '1000' cannot be converted to a 'byte' // if (b is 1000) { } // error: cannot convert 1000 to byte Diagnostic(ErrorCode.ERR_ConstOutOfRange, "1000").WithArguments("1000", "byte").WithLocation(13, 18), // (9,55): error CS0165: Use of unassigned local variable 't' // if (s is string t) { } else Console.WriteLine(t); Diagnostic(ErrorCode.ERR_UseDefViolation, "t").WithArguments("t").WithLocation(9, 55) ); } [Fact] public void PatternInCtorInitializer() { var source = @"using System; public class X { public static void Main() { new D(1); new D(10); new D(1.2); } } class D { public D(object o) : this(o is int x && x >= 5) {} public D(bool b) { Console.WriteLine(b); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var expectedOutput = @"False True False"; var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void PatternInCatchFilter() { var source = @"using System; public class X { public static void Main() { M(1); M(10); M(1.2); } private static void M(object o) { try { throw new Exception(); } catch (Exception) when (o is int x && x >= 5) { Console.WriteLine($""Yes for {o}""); } catch (Exception) { Console.WriteLine($""No for {o}""); } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); using (new EnsureInvariantCulture()) { var expectedOutput = @"No for 1 Yes for 10 No for 1.2"; var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } } [ConditionalFact(typeof(DesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28026")] public void PatternInFieldInitializer() { var source = @"using System; public class X { static object o1 = 1; static object o2 = 10; static object o3 = 1.2; static bool b1 = M(o1, (o1 is int x && x >= 5)), b2 = M(o2, (o2 is int x && x >= 5)), b3 = M(o3, (o3 is int x && x >= 5)); public static void Main() { } private static bool M(object o, bool result) { Console.WriteLine($""{result} for {o}""); return result; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); using (new EnsureInvariantCulture()) { var expectedOutput = @"False for 1 True for 10 False for 1.2"; var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } } [Fact] public void PatternInExpressionBodiedMethod() { var source = @"using System; public class X { static object o1 = 1; static object o2 = 10; static object o3 = 1.2; static bool B1() => M(o1, (o1 is int x && x >= 5)); static bool B2 => M(o2, (o2 is int x && x >= 5)); static bool B3 => M(o3, (o3 is int x && x >= 5)); public static void Main() { var r = B1() | B2 | B3; } private static bool M(object o, bool result) { Console.WriteLine($""{result} for {o}""); return result; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); using (new EnsureInvariantCulture()) { var expectedOutput = @"False for 1 True for 10 False for 1.2"; var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } } [Fact, WorkItem(8778, "https://github.com/dotnet/roslyn/issues/8778")] public void PatternInExpressionBodiedLocalFunction() { var source = @"using System; public class X { static object o1 = 1; static object o2 = 10; static object o3 = 1.2; public static void Main() { bool B1() => M(o1, (o1 is int x && x >= 5)); bool B2() => M(o2, (o2 is int x && x >= 5)); bool B3() => M(o3, (o3 is int x && x >= 5)); var r = B1() | B2() | B3(); } private static bool M(object o, bool result) { Console.WriteLine($""{result} for {o}""); return result; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); using (new EnsureInvariantCulture()) { var expectedOutput = @"False for 1 True for 10 False for 1.2"; var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } } [Fact, WorkItem(8778, "https://github.com/dotnet/roslyn/issues/8778")] public void PatternInExpressionBodiedLambda() { var source = @"using System; public class X { public static void Main() { object o1 = 1; object o2 = 10; object o3 = 1.2; Func<object, bool> B1 = o => M(o, (o is int x && x >= 5)); B1(o1); Func<bool> B2 = () => M(o2, (o2 is int x && x >= 5)); B2(); Func<bool> B3 = () => M(o3, (o3 is int x && x >= 5)); B3(); } private static bool M(object o, bool result) { Console.WriteLine($""{result} for {o}""); return result; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); using (new EnsureInvariantCulture()) { var expectedOutput = @"False for 1 True for 10 False for 1.2"; var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } } [Fact] public void PatternInBadPlaces() { var source = @"using System; [Obsolete("""" is string s ? s : """")] public class X { public static void Main() { } private static void M(string p = """" is object o ? o.ToString() : """") { } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (2,11): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [Obsolete("" is string s ? s : "")] Diagnostic(ErrorCode.ERR_BadAttributeArgument, @""""" is string s ? s : """"").WithLocation(2, 11), // (8,38): error CS1736: Default parameter value for 'p' must be a compile-time constant // private static void M(string p = "" is object o ? o.ToString() : "") Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, @""""" is object o ? o.ToString() : """"").WithArguments("p").WithLocation(8, 38) ); } [Fact] public void PatternInSwitchAndForeach() { var source = @"using System; public class X { public static void Main() { object o1 = 1; object o2 = 10; object o3 = 1.2; object oa = new object[] { 1, 10, 1.2 }; foreach (var o in oa is object[] z ? z : new object[0]) { switch (o is int x && x >= 5) { case true: M(o, true); break; case false: M(o, false); break; default: throw null; } } } private static bool M(object o, bool result) { Console.WriteLine($""{result} for {o}""); return result; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); using (new EnsureInvariantCulture()) { var expectedOutput = @"False for 1 True for 10 False for 1.2"; var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } } [Fact] public void GeneralizedSwitchStatement() { Uri u = new Uri("http://www.microsoft.com"); var source = @"using System; public struct X { public static void Main() { var oa = new object[] { 1, 10, 20L, 1.2, ""goo"", true, null, new X(), new Exception(""boo"") }; foreach (var o in oa) { switch (o) { default: Console.WriteLine($""class {o.GetType().Name} {o}""); break; case 1: Console.WriteLine(""one""); break; case int i: Console.WriteLine($""int {i}""); break; case long i: Console.WriteLine($""long {i}""); break; case double d: Console.WriteLine($""double {d}""); break; case null: Console.WriteLine($""null""); break; case ValueType z: Console.WriteLine($""struct {z.GetType().Name} {z}""); break; } } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); using (new EnsureInvariantCulture()) { var expectedOutput = @"one int 10 long 20 double 1.2 class String goo struct Boolean True null struct X X class Exception System.Exception: boo "; var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } } [Fact] public void PatternVariableDefiniteAssignment() { var source = @"using System; public class X { public static void Main() { object o = new X(); if (o is X x1) Console.WriteLine(x1); // OK if (!(o is X x2)) Console.WriteLine(x2); // error if (o is X x3 || true) Console.WriteLine(x3); // error switch (o) { case X x4: default: Console.WriteLine(x4); // error break; } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (8,45): error CS0165: Use of unassigned local variable 'x2' // if (!(o is X x2)) Console.WriteLine(x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(8, 45), // (9,50): error CS0165: Use of unassigned local variable 'x3' // if (o is X x3 || true) Console.WriteLine(x3); Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(9, 50), // (14,35): error CS0165: Use of unassigned local variable 'x4' // Console.WriteLine(x4); // error Diagnostic(ErrorCode.ERR_UseDefViolation, "x4").WithArguments("x4").WithLocation(14, 35) ); } [Fact] public void PatternVariablesAreMutable() { var source = @" public class X { public static void Main() { if (12 is var x) { x = x + 1; x++; M1(ref x); M2(out x); } } public static void M1(ref int x) {} public static void M2(out int x) { x = 1; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); } [Fact] public void If_01() { var source = @" public class X { public static void Main() { Test(1); Test(2); } public static void Test(int val) { if (Dummy(val == 1, val is var x1, x1)) { System.Console.WriteLine(""true""); System.Console.WriteLine(x1); } else { System.Console.WriteLine(""false""); System.Console.WriteLine(x1); } System.Console.WriteLine(x1); } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 true 1 1 2 false 2 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(4, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void If_02() { var source = @" public class X { public static void Main() { bool f = true; if (f) if (Dummy(f, (f ? 1 : 2) is var x1, x1)) ; if (f) { if (Dummy(f, (f ? 3 : 4) is var x1, x1)) ; } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0]); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]); } [Fact] public void Lambda_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static bool Test1() { System.Func<bool> l = () => 1 is int x1 && Dummy(x1); return l(); } static bool Dummy(int x) { System.Console.WriteLine(x); return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 True"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").Single(); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/28026")] public void Query_01() { var source = @" using System.Linq; public class X { public static void Main() { Test1(); } static void Test1() { var res = from x1 in new[] { 1 is var y1 && Print(y1) ? 1 : 0} from x2 in new[] { 2 is var y2 && Print(y2) ? 1 : 0} join x3 in new[] { 3 is var y3 && Print(y3) ? 1 : 0} on 4 is var y4 && Print(y4) ? 1 : 0 equals 5 is var y5 && Print(y5) ? 1 : 0 where 6 is var y6 && Print(y6) orderby 7 is var y7 && Print(y7), 8 is var y8 && Print(y8) group 9 is var y9 && Print(y9) by 10 is var y10 && Print(y10) into g let x11 = 11 is var y11 && Print(y11) select 12 is var y12 && Print(y12); res.ToArray(); } static bool Print(object x) { System.Console.WriteLine(x); return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: @"1 3 5 2 4 6 7 8 10 9 11 12 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); for (int i = 1; i < 13; i++) { var id = "y" + i; var yDecl = GetPatternDeclarations(tree, id).Single(); var yRef = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(name => name.Identifier.ValueText == id).Single(); VerifyModelForDeclarationOrVarSimplePattern(model, yDecl, yRef); } } [Fact] public void Query_02() { var source = @" using System.Linq; public class X { public static void Main() { Test1(); } static void Test1() { var res = from x1 in new[] { 1 is var y1 && Print(y1) ? 2 : 0} select Print(x1); res.ToArray(); } static bool Print(object x) { System.Console.WriteLine(x); return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var yDecl = GetPatternDeclaration(tree, "y1"); var yRef = GetReferences(tree, "y1").Single(); VerifyModelForDeclarationOrVarSimplePattern(model, yDecl, yRef); } [Fact] public void ExpressionBodiedFunctions_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static bool Test1() => 1 is int x1 && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] public void ExpressionBodiedProperties_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); System.Console.WriteLine(new X()[0]); } static bool Test1 => 2 is int x1 && Dummy(x1); bool this[object x] => 1 is int x1 && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"2 True 1 True"); } [Fact] public void FieldInitializers_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); } static bool Test1 = 1 is int x1 && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 True"); CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (9,34): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater. // static bool Test1 = 1 is int x1 && Dummy(x1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(9, 34) ); } [Fact, WorkItem(10487, "https://github.com/dotnet/roslyn/issues/10487")] public void FieldInitializers_03() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); new X().M(); } void M() { System.Console.WriteLine(Test2); } static bool Test1 = 1 is int x1 && Dummy(() => x1); bool Test2 = 2 is int x1 && Dummy(() => x1); static bool Dummy(System.Func<int> x) { System.Console.WriteLine(x()); return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 True 2 True"); } [Fact] [WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")] public void FieldInitializers_04() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static System.Func<bool> Test1 = () => 1 is int x1 && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] public void PropertyInitializers_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1); } static bool Test1 {get;} = 1 is int x1 && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 True"); CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (9,41): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater. // static bool Test1 {get;} = 1 is int x1 && Dummy(x1); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(9, 41) ); } [Fact] [WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")] public void PropertyInitializers_02() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static System.Func<bool> Test1 {get;} = () => 1 is int x1 && Dummy(x1); static bool Dummy(int x) { System.Console.WriteLine(x); return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 True"); } [Fact] public void ConstructorInitializers_01() { var source = @" public class X { public static void Main() { var x = new D(); } } class D : C { public D(object o) : base(2 is var x1 && Dummy(x1)) { System.Console.WriteLine(o); } public D() : this(1 is int x1 && Dummy(x1)) { } static bool Dummy(int x) { System.Console.WriteLine(x); return true; } } class C { public C(object b) { System.Console.WriteLine(b); } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 2 True True"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0]); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]); Assert.Equal("System.Int32", ((ILocalSymbol)compilation.GetSemanticModel(tree).GetDeclaredSymbol(x1Decl[0])).Type.ToTestDisplayString()); CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (12,40): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater. // public D(object o) : base(2 is var x1 && Dummy(x1)) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(12, 40), // (17,32): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater. // public D() : this(1 is int x1 && Dummy(x1)) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(17, 32) ); } [Fact] [WorkItem(16935, "https://github.com/dotnet/roslyn/issues/16935")] public void ConstructorInitializers_02() { var source = @" public class X { public static void Main() { var x = new D(); } } class D : C { public D(System.Func<bool> o) : base(() => 2 is int x1 && Dummy(x1)) { System.Console.WriteLine(o()); } public D() : this(() => 1 is int x1 && Dummy(x1)) { } static bool Dummy(int x) { System.Console.WriteLine(x); return true; } } class C { public C(System.Func<bool> b) { System.Console.WriteLine(b()); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"2 True 1 True"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0]); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]); } [Fact] public void Switch_01() { var source = @" public class X { public static void Main() { Test1(0); Test1(1); } static bool Dummy1(bool val, params object[] x) {return val;} static T Dummy2<T>(T val, params object[] x) {return val;} static void Test1(int val) { switch (Dummy2(val, ""Test1 {0}"" is var x1)) { case 0 when Dummy1(true, ""case 0"" is var y1): System.Console.WriteLine(x1, y1); break; case int z1: System.Console.WriteLine(x1, z1); break; } System.Console.WriteLine(x1); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"Test1 case 0 Test1 {0} Test1 1 Test1 {0}"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void Switch_02() { var source = @" public class X { public static void Main() { bool f = true; if (f) switch (Dummy(f, (f ? 1 : 2) is var x1, x1)) {} if (f) { switch (Dummy(f, (f ? 3 : 4) is var x1, x1)) {} } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0]); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]); } [Fact] public void Using_01() { var source = @" public class X { public static void Main() { using (System.IDisposable d1 = Dummy(new C(""a""), new C(""b"") is var x1), d2 = Dummy(new C(""c""), new C(""d"") is var x2)) { System.Console.WriteLine(d1); System.Console.WriteLine(x1); System.Console.WriteLine(d2); System.Console.WriteLine(x2); } using (Dummy(new C(""e""), new C(""f"") is var x1)) { System.Console.WriteLine(x1); } } static System.IDisposable Dummy(System.IDisposable x, params object[] y) {return x;} } class C : System.IDisposable { private readonly string _val; public C(string val) { _val = val; } public void Dispose() { System.Console.WriteLine(""Disposing {0}"", _val); } public override string ToString() { return _val; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"a b c d Disposing c Disposing a f Disposing e"); } [Fact] public void LocalDeclarationStmt_01() { var source = @" public class X { public static void Main() { object d1 = Dummy(new C(""a""), new C(""b"") is var x1, x1), d2 = Dummy(new C(""c""), new C(""d"") is var x2, x2); System.Console.WriteLine(d1); System.Console.WriteLine(d2); System.Console.WriteLine(x1); } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"b d a c b"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").ToArray(); var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void LocalDeclarationStmt_02() { var source = @" public class X { public static void Main() { if (true) { object d1 = Dummy(new C(""a""), new C(""b"") is var x1, x1); } } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"b"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").ToArray(); var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void DeconstructionDeclarationStmt_01() { var source = @" public class X { public static void Main() { (object d1, object d2) = (Dummy(new C(""a""), (new C(""b"") is var x1), x1), Dummy(new C(""c""), (new C(""d"") is var x2), x2)); System.Console.WriteLine(d1); System.Console.WriteLine(d2); System.Console.WriteLine(x1); } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b d a c b"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void DeconstructionDeclarationStmt_02() { var source = @" public class X { public static void Main() { if (true) { (object d1, object d2) = (Dummy(new C(""a""), (new C(""b"") is var x1), x1), x1); } } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").ToArray(); var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void DeconstructionDeclarationStmt_03() { var source = @" public class X { public static void Main() { var (d1, (d2, d3)) = (Dummy(new C(""a""), (new C(""b"") is var x1), x1), (Dummy(new C(""c""), (new C(""d"") is var x2), x2), Dummy(new C(""e""), (new C(""f"") is var x3), x3))); System.Console.WriteLine(d1); System.Console.WriteLine(d2); System.Console.WriteLine(d3); System.Console.WriteLine(x1); System.Console.WriteLine(x2); System.Console.WriteLine(x3); } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b d f a c e b d f"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").ToArray(); var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); var x2Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x2").ToArray(); var x2Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x2").ToArray(); Assert.Equal(1, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl[0], x2Ref); var x3Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x3").ToArray(); var x3Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x3").ToArray(); Assert.Equal(1, x3Decl.Length); Assert.Equal(2, x3Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl[0], x3Ref); } [Fact] [CompilerTrait(CompilerFeature.Tuples)] public void DeconstructionDeclarationStmt_04() { var source = @" public class X { public static void Main() { (var d1, (var d2, var d3)) = (Dummy(new C(""a""), (new C(""b"") is var x1), x1), (Dummy(new C(""c""), (new C(""d"") is var x2), x2), Dummy(new C(""e""), (new C(""f"") is var x3), x3))); System.Console.WriteLine(d1); System.Console.WriteLine(d2); System.Console.WriteLine(d3); System.Console.WriteLine(x1); System.Console.WriteLine(x2); System.Console.WriteLine(x3); } static object Dummy(object x, object y, object z) { System.Console.WriteLine(z); return x; } } class C { private readonly string _val; public C(string val) { _val = val; } public override string ToString() { return _val; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"b d f a c e b d f"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); var x2Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x2").ToArray(); var x2Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x2").ToArray(); Assert.Equal(1, x2Decl.Length); Assert.Equal(2, x2Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl[0], x2Ref); var x3Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x3").ToArray(); var x3Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x3").ToArray(); Assert.Equal(1, x3Decl.Length); Assert.Equal(2, x3Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl[0], x3Ref); } [Fact] public void While_01() { var source = @" public class X { public static void Main() { bool f = true; while (Dummy(f, (f ? 1 : 2) is var x1, x1)) { System.Console.WriteLine(x1); f = false; } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 1 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void While_02() { var source = @" public class X { public static void Main() { bool f = true; if (f) while (Dummy(f, (f ? 1 : 2) is var x1, x1)) break; if (f) { while (Dummy(f, (f ? 3 : 4) is var x1, x1)) break; } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0]); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]); } [Fact] public void While_03() { var source = @" public class X { public static void Main() { int f = 1; var l = new System.Collections.Generic.List<System.Action>(); while (Dummy(f < 3, f is var x1, x1)) { l.Add(() => System.Console.WriteLine(x1)); f++; } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2 3 -- 1 2 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void While_04() { var source = @" public class X { public static void Main() { int f = 1; var l = new System.Collections.Generic.List<System.Action>(); while (Dummy(f < 3, f is var x1, x1, l, () => System.Console.WriteLine(x1))) { f++; } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2 3 -- 1 2 3 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void While_05() { var source = @" public class X { public static void Main() { int f = 1; var l = new System.Collections.Generic.List<System.Action>(); while (Dummy(f < 3, f is var x1, x1, l, () => System.Console.WriteLine(x1))) { l.Add(() => System.Console.WriteLine(x1)); f++; } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"1 2 3 -- 1 1 2 2 3 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void Do_01() { var source = @" public class X { public static void Main() { bool f; do { f = false; } while (Dummy(f, (f ? 1 : 2) is var x1, x1)); } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void Do_02() { var source = @" public class X { public static void Main() { bool f = true; if (f) do ; while (Dummy(f, (f ? 1 : 2) is var x1, x1) && false); if (f) { do ; while (Dummy(f, (f ? 3 : 4) is var x1, x1) && false); } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0]); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]); } [Fact] public void Do_03() { var source = @" public class X { public static void Main() { int f = 1; var l = new System.Collections.Generic.List<System.Action>(); do { ; } while (Dummy(f < 3, (f++) is var x1, x1, l, () => System.Console.WriteLine(x1))); System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 2 3 -- 1 2 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void For_01() { var source = @" public class X { public static void Main() { bool f = true; for (Dummy(f, (f ? 10 : 20) is var x0, x0); Dummy(f, (f ? 1 : 2) is var x1, x1); Dummy(f, (f ? 100 : 200) is var x2, x2), Dummy(true, null, x2)) { System.Console.WriteLine(x0); System.Console.WriteLine(x1); f = false; } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"10 1 10 1 200 200 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetPatternDeclarations(tree, "x0").Single(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(2, x0Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x0Decl, x0Ref); var x1Decl = GetPatternDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref); var x2Decl = GetPatternDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref); } [Fact] public void For_02() { var source = @" public class X { public static void Main() { bool f = true; for (Dummy(f, (f ? 10 : 20) is var x0, x0); Dummy(f, (f ? 1 : 2) is var x1, x1); f = false, Dummy(f, (f ? 100 : 200) is var x2, x2), Dummy(true, null, x2)) { System.Console.WriteLine(x0); System.Console.WriteLine(x1); } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"10 1 10 1 200 200 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetPatternDeclarations(tree, "x0").Single(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(2, x0Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x0Decl, x0Ref); var x1Decl = GetPatternDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref); var x2Decl = GetPatternDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").ToArray(); Assert.Equal(2, x2Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref); } [Fact] public void For_03() { var source = @" public class X { public static void Main() { var l = new System.Collections.Generic.List<System.Action>(); for (bool f = 1 is var x0; Dummy(x0 < 3, x0*10 is var x1, x1); x0++) { l.Add(() => System.Console.WriteLine(""{0} {1}"", x0, x1)); } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"10 20 30 -- 3 10 3 20 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetPatternDeclarations(tree, "x0").ToArray(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(1, x0Decl.Length); Assert.Equal(4, x0Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x0Decl[0], x0Ref); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void For_04() { var source = @" public class X { public static void Main() { var l = new System.Collections.Generic.List<System.Action>(); for (bool f = 1 is var x0; Dummy(x0 < 3, x0*10 is var x1, x1, l, () => System.Console.WriteLine(""{0} {1}"", x0, x1)); x0++) { } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"10 20 30 -- 3 10 3 20 3 30 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetPatternDeclarations(tree, "x0").ToArray(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(1, x0Decl.Length); Assert.Equal(4, x0Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x0Decl[0], x0Ref); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void For_05() { var source = @" public class X { public static void Main() { var l = new System.Collections.Generic.List<System.Action>(); for (bool f = 1 is var x0; Dummy(x0 < 3, x0*10 is var x1, x1, l, () => System.Console.WriteLine(""{0} {1}"", x0, x1)); x0++) { l.Add(() => System.Console.WriteLine(""{0} {1}"", x0, x1)); } System.Console.WriteLine(""--""); foreach (var d in l) { d(); } } static bool Dummy(bool x, object y, object z, System.Collections.Generic.List<System.Action> l, System.Action d) { l.Add(d); System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: @"10 20 30 -- 3 10 3 10 3 20 3 20 3 30 "); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x0Decl = GetPatternDeclarations(tree, "x0").ToArray(); var x0Ref = GetReferences(tree, "x0").ToArray(); Assert.Equal(1, x0Decl.Length); Assert.Equal(5, x0Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x0Decl[0], x0Ref); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void Foreach_01() { var source = @" public class X { public static void Main() { bool f = true; foreach (var i in Dummy(3 is var x1, x1)) { System.Console.WriteLine(x1); } } static System.Collections.IEnumerable Dummy(object y, object z) { System.Console.WriteLine(z); return ""a""; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"3 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref); } [Fact] public void Lock_01() { var source = @" public class X { public static void Main() { lock (Dummy(""lock"" is var x1, x1)) { System.Console.WriteLine(x1); } System.Console.WriteLine(x1); } static object Dummy(object y, object z) { System.Console.WriteLine(z); return new object(); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"lock lock lock"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(3, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void Lock_02() { var source = @" public class X { public static void Main() { bool f = true; if (f) lock (Dummy(f, (f ? 1 : 2) is var x1, x1)) {} if (f) { lock (Dummy(f, (f ? 3 : 4) is var x1, x1)) {} } } static object Dummy(bool x, object y, object z) { System.Console.WriteLine(z); return x; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 3"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0]); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]); } [Fact] public void Fixed_01() { var source = @" public unsafe class X { public static void Main() { fixed (int* p = Dummy(""fixed"" is var x1, x1)) { System.Console.WriteLine(x1); } } static int[] Dummy(object y, object z) { System.Console.WriteLine(z); return new int[1]; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe.WithAllowUnsafe(true)); CompileAndVerify(compilation, verify: Verification.Fails, expectedOutput: @"fixed fixed"); } [Fact] public void Yield_01() { var source = @" public class X { public static void Main() { foreach (var o in Test()) {} } static System.Collections.IEnumerable Test() { yield return Dummy(""yield1"" is var x1, x1); yield return Dummy(""yield2"" is var x2, x2); System.Console.WriteLine(x1); } static object Dummy(object y, object z) { System.Console.WriteLine(z); return new object(); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"yield1 yield2 yield1"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void Yield_02() { var source = @" public class X { public static void Main() { foreach (var o in Test()) {} } static System.Collections.IEnumerable Test() { bool f = true; if (f) yield return Dummy(""yield1"" is var x1, x1); if (f) { yield return Dummy(""yield2"" is var x1, x1); } } static object Dummy(object y, object z) { System.Console.WriteLine(z); return new object(); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"yield1 yield2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").ToArray(); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0]); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]); } [Fact] public void Return_01() { var source = @" public class X { public static void Main() { Test(); } static object Test() { return Dummy(""return"" is var x1, x1); } static object Dummy(object y, object z) { System.Console.WriteLine(z); return new object(); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"return"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").ToArray(); var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void Return_02() { var text = @" public class Cls { public static void Main() { Test0(true); Test0(false); } static object Test0(bool val) { if (val) return Test2(1 is var x1, x1); if (!val) { return Test2(2 is var x1, x1); } return null; } static object Test2(object x, object y) { System.Console.Write(y); return x; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: "12").VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").ToArray(); var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0]); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]); } [Fact] public void Throw_01() { var source = @" public class X { public static void Main() { Test(); } static void Test() { try { throw Dummy(""throw"" is var x1, x1); } catch { } } static System.Exception Dummy(object y, object z) { System.Console.WriteLine(z); return new System.ArgumentException(); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"throw"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").ToArray(); var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void Throw_02() { var source = @" public class X { public static void Main() { Test(true); Test(false); } static void Test(bool val) { try { if (val) throw Dummy(""throw 1"" is var x1, x1); if (!val) { throw Dummy(""throw 2"" is var x1, x1); } } catch { } } static System.Exception Dummy(object y, object z) { System.Console.WriteLine(z); return new System.ArgumentException(); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"throw 1 throw 2"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").ToArray(); var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").ToArray(); Assert.Equal(2, x1Decl.Length); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref[0]); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[1], x1Ref[1]); } [Fact] public void Catch_01() { var source = @" public class X { public static void Main() { try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(e is var x1, x1)) { System.Console.WriteLine(x1.GetType()); } } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclaration(tree, "x1"); var x1Ref = GetReferences(tree, "x1").ToArray(); Assert.Equal(2, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl, x1Ref); } [Fact] public void Catch_02() { var source = @" public class X { public static void Main() { try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(e is var x1, x1)) { System.Action d = () => { System.Console.WriteLine(x1.GetType()); }; System.Console.WriteLine(x1.GetType()); d(); } } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException System.InvalidOperationException"); } [Fact] public void Catch_03() { var source = @" public class X { public static void Main() { try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(e is var x1, x1)) { System.Action d = () => { e = new System.NullReferenceException(); System.Console.WriteLine(x1.GetType()); }; System.Console.WriteLine(x1.GetType()); d(); System.Console.WriteLine(e.GetType()); } } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException System.InvalidOperationException System.NullReferenceException"); } [Fact] public void Catch_04() { var source = @" public class X { public static void Main() { try { throw new System.InvalidOperationException(); } catch (System.Exception e) when (Dummy(e is var x1, x1)) { System.Action d = () => { e = new System.NullReferenceException(); }; System.Console.WriteLine(x1.GetType()); d(); System.Console.WriteLine(e.GetType()); } } static bool Dummy(object y, object z) { System.Console.WriteLine(z.GetType()); return true; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"System.InvalidOperationException System.InvalidOperationException System.NullReferenceException"); } [Fact] public void Labeled_01() { var text = @" public class Cls { public static void Main() { a: Test1(2 is var x1); System.Console.WriteLine(x1); } static object Test1(bool x) { return null; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: "2").VerifyDiagnostics( // (6,1): warning CS0164: This label has not been referenced // a: Test1(2 is var x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(6, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").ToArray(); var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact] public void Labeled_02() { var text = @" public class Cls { public static void Main() { Test0(); } static object Test0() { bool test = true; if (test) { a: Test2(2 is var x1, x1); } return null; } static object Test2(object x, object y) { System.Console.Write(y); return x; } }"; var compilation = CreateCompilation(text, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular); CompileAndVerify(compilation, expectedOutput: "2").VerifyDiagnostics( // (15,1): warning CS0164: This label has not been referenced // a: Test2(2 is var x1, x1); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "a").WithLocation(15, 1) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Where(p => p.Identifier.ValueText == "x1").ToArray(); var x1Ref = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x1").ToArray(); Assert.Equal(1, x1Decl.Length); Assert.Equal(1, x1Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x1Decl[0], x1Ref); } [Fact, WorkItem(10465, "https://github.com/dotnet/roslyn/issues/10465")] public void Constants_Fail() { var source = @" using System; public class X { public static void Main() { Console.WriteLine(1L is string); // warning: type mismatch Console.WriteLine(1 is int[]); // warning: expression is never of the provided type Console.WriteLine(1L is string s); // error: type mismatch Console.WriteLine(1 is int[] a); // error: expression is never of the provided type } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (7,27): warning CS0184: The given expression is never of the provided ('string') type // Console.WriteLine(1L is string); // warning: type mismatch Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "1L is string").WithArguments("string").WithLocation(7, 27), // (8,27): warning CS0184: The given expression is never of the provided ('int[]') type // Console.WriteLine(1 is int[]); // warning: expression is never of the provided type Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "1 is int[]").WithArguments("int[]").WithLocation(8, 27), // (10,33): error CS8121: An expression of type 'long' cannot be handled by a pattern of type 'string'. // Console.WriteLine(1L is string s); // error: type mismatch Diagnostic(ErrorCode.ERR_PatternWrongType, "string").WithArguments("long", "string").WithLocation(10, 33), // (11,32): error CS8121: An expression of type 'int' cannot be handled by a pattern of type 'int[]'. // Console.WriteLine(1 is int[] a); // error: expression is never of the provided type Diagnostic(ErrorCode.ERR_PatternWrongType, "int[]").WithArguments("int", "int[]").WithLocation(11, 32) ); } [Fact, WorkItem(10465, "https://github.com/dotnet/roslyn/issues/10465")] public void Types_Pass() { var source = @" using System; public class X { public static void Main() { Console.WriteLine(1 is 1); // true Console.WriteLine(1L is int.MaxValue); // OK, but false Console.WriteLine(1 is int.MaxValue); // false Console.WriteLine(int.MaxValue is int.MaxValue); // true Console.WriteLine(""goo"" is System.String); // true Console.WriteLine(Int32.MaxValue is Int32.MaxValue); // true Console.WriteLine(new int[] {1, 2} is int[] a); // true object o = null; switch (o) { case int[] b: break; case int.MaxValue: // constant, not a type break; case int i: break; case null: Console.WriteLine(""null""); break; } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (7,27): warning CS8417: The given expression always matches the provided constant. // Console.WriteLine(1 is 1); // true Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesConstant, "1 is 1").WithLocation(7, 27), // (8,27): warning CS8416: The given expression never matches the provided pattern. // Console.WriteLine(1L is int.MaxValue); // OK, but false Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1L is int.MaxValue").WithLocation(8, 27), // (9,27): warning CS8416: The given expression never matches the provided pattern. // Console.WriteLine(1 is int.MaxValue); // false Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "1 is int.MaxValue").WithLocation(9, 27), // (10,27): warning CS8417: The given expression always matches the provided constant. // Console.WriteLine(int.MaxValue is int.MaxValue); // true Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesConstant, "int.MaxValue is int.MaxValue").WithLocation(10, 27), // (11,27): warning CS0183: The given expression is always of the provided ('string') type // Console.WriteLine("goo" is System.String); // true Diagnostic(ErrorCode.WRN_IsAlwaysTrue, @"""goo"" is System.String").WithArguments("string").WithLocation(11, 27), // (12,27): warning CS8417: The given expression always matches the provided constant. // Console.WriteLine(Int32.MaxValue is Int32.MaxValue); // true Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesConstant, "Int32.MaxValue is Int32.MaxValue").WithLocation(12, 27) ); CompileAndVerify(compilation, expectedOutput: @"True False False True True True True null"); } [Fact, WorkItem(10459, "https://github.com/dotnet/roslyn/issues/10459")] public void Typeswitch_01() { var source = @" using System; public class X { public static void Main(string[] args) { switch (args.GetType()) { case typeof(string): Console.WriteLine(""string""); break; case typeof(string[]): Console.WriteLine(""string[]""); break; case null: Console.WriteLine(""null""); break; default: Console.WriteLine(""default""); break; } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (9,18): error CS0150: A constant value is expected // case typeof(string): Diagnostic(ErrorCode.ERR_ConstantExpected, "typeof(string)").WithLocation(9, 18), // (12,18): error CS0150: A constant value is expected // case typeof(string[]): Diagnostic(ErrorCode.ERR_ConstantExpected, "typeof(string[])").WithLocation(12, 18) ); // If we support switching on System.Type as proposed, the expectation would be // something like CompileAndVerify(compilation, expectedOutput: @"string[]"); } [Fact, WorkItem(10529, "https://github.com/dotnet/roslyn/issues/10529")] public void MissingTypeAndProperty() { var source = @" class Program { public static void Main(string[] args) { { if (obj.Property is var o) { } // `obj` doesn't exist. } { var obj = new object(); if (obj. is var o) { } } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (11,22): error CS1001: Identifier expected // if (obj. is var o) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, "is").WithLocation(11, 22), // (7,17): error CS0103: The name 'obj' does not exist in the current context // if (obj.Property is var o) { } // `obj` doesn't exist. Diagnostic(ErrorCode.ERR_NameNotInContext, "obj").WithArguments("obj").WithLocation(7, 17) ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); foreach (var isExpression in tree.GetRoot().DescendantNodes().OfType<IsPatternExpressionSyntax>()) { var symbolInfo = model.GetSymbolInfo(isExpression.Expression); Assert.Null(symbolInfo.Symbol); Assert.True(symbolInfo.CandidateSymbols.IsDefaultOrEmpty); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); } } [Fact] public void MixedDecisionTree() { var source = @" using System; public class X { public static void Main() { M(null); M(1); M((byte)1); M((short)1); M(2); M((byte)2); M((short)2); M(""hmm""); M(""bar""); M(""baz""); M(6); } public static void M(object o) { switch (o) { case ""hmm"": Console.WriteLine(""hmm""); break; case null: Console.WriteLine(""null""); break; case 1: Console.WriteLine(""int 1""); break; case ((byte)1): Console.WriteLine(""byte 1""); break; case ((short)1): Console.WriteLine(""short 1""); break; case ""bar"": Console.WriteLine(""bar""); break; case object t when t != o: Console.WriteLine(""impossible""); break; case 2: Console.WriteLine(""int 2""); break; case ((byte)2): Console.WriteLine(""byte 2""); break; case ((short)2): Console.WriteLine(""short 2""); break; case ""baz"": Console.WriteLine(""baz""); break; default: Console.WriteLine(""other "" + o); break; } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: @"null int 1 byte 1 short 1 int 2 byte 2 short 2 hmm bar baz other 6"); } [Fact] public void SemanticAnalysisWithPatternInCsharp6() { var source = @"class Program { public static void Main(string[] args) { switch (args.Length) { case 1 when true: break; } } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular6); compilation.VerifyDiagnostics( // (7,13): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // case 1 when true: Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "case 1 when true:").WithArguments("pattern matching", "7.0").WithLocation(7, 13) ); } [Fact, WorkItem(11379, "https://github.com/dotnet/roslyn/issues/11379")] public void DeclarationPatternWithStaticClass() { var source = @"class Program { public static void Main(string[] args) { object o = args; switch (o) { case StaticType t: break; } } } public static class StaticType { } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (8,18): error CS0723: Cannot declare a variable of static type 'StaticType' // case StaticType t: Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "StaticType").WithArguments("StaticType").WithLocation(8, 18) ); } [Fact] public void PatternVariablesAreMutable02() { var source = @"class Program { public static void Main(string[] args) { object o = "" whatever ""; if (o is string s) { s = s.Trim(); System.Console.WriteLine(s); } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: "whatever"); } [Fact, WorkItem(12996, "https://github.com/dotnet/roslyn/issues/12996")] public void TypeOfAVarPatternVariable() { var source = @" class Program { public static void Main(string[] args) { } public static void Test(int val) { if (val is var o1) { System.Console.WriteLine(o1); } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var tree = compilation.SyntaxTrees[0]; var model1 = compilation.GetSemanticModel(tree); var declaration = tree.GetRoot().DescendantNodes().OfType<IsPatternExpressionSyntax>().Single(); var o1 = GetReferences(tree, "o1").Single(); var typeInfo1 = model1.GetTypeInfo(declaration); Assert.Equal(SymbolKind.NamedType, typeInfo1.Type.Kind); Assert.Equal("System.Boolean", typeInfo1.Type.ToTestDisplayString()); typeInfo1 = model1.GetTypeInfo(o1); Assert.Equal(SymbolKind.NamedType, typeInfo1.Type.Kind); Assert.Equal("System.Int32", typeInfo1.Type.ToTestDisplayString()); var model2 = compilation.GetSemanticModel(tree); var typeInfo2 = model2.GetTypeInfo(o1); Assert.Equal(SymbolKind.NamedType, typeInfo2.Type.Kind); Assert.Equal("System.Int32", typeInfo2.Type.ToTestDisplayString()); } [Fact] [WorkItem(13417, "https://github.com/dotnet/roslyn/issues/13417")] public void FixedFieldSize() { var text = @" unsafe struct S { fixed int F1[3 is var x1 ? x1 : 3]; fixed int F2[3 is var x2 ? 3 : 3, x2]; } "; var compilation = CreateCompilation(text, options: TestOptions.ReleaseDebugDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x1Decl = GetPatternDeclarations(tree, "x1").Single(); var x1Ref = GetReferences(tree, "x1").Single(); Assert.True(((ITypeSymbol)compilation.GetSemanticModel(tree).GetTypeInfo(x1Ref).Type).IsErrorType()); VerifyModelNotSupported(model, x1Decl, x1Ref); var x2Decl = GetPatternDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelNotSupported(model, x2Decl, x2Ref); Assert.True(((ITypeSymbol)compilation.GetSemanticModel(tree).GetTypeInfo(x2Ref).Type).IsErrorType()); compilation.VerifyDiagnostics( // (5,17): error CS7092: A fixed buffer may only have one dimension. // fixed int F2[3 is var x2 ? 3 : 3, x2]; Diagnostic(ErrorCode.ERR_FixedBufferTooManyDimensions, "[3 is var x2 ? 3 : 3, x2]").WithLocation(5, 17), // (5,18): error CS0133: The expression being assigned to 'S.F2' must be constant // fixed int F2[3 is var x2 ? 3 : 3, x2]; Diagnostic(ErrorCode.ERR_NotConstantExpression, "3 is var x2 ? 3 : 3").WithArguments("S.F2").WithLocation(5, 18), // (4,18): error CS0133: The expression being assigned to 'S.F1' must be constant // fixed int F1[3 is var x1 ? x1 : 3]; Diagnostic(ErrorCode.ERR_NotConstantExpression, "3 is var x1 ? x1 : 3").WithArguments("S.F1").WithLocation(4, 18) ); } [Fact, WorkItem(13316, "https://github.com/dotnet/roslyn/issues/13316")] public void TypeAsExpressionInIsPattern() { var source = @"namespace CS7 { class T1 { public int a = 2; } class Program { static void Main(string[] args) { if (T1 is object i) { } } } }"; CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics( // (8,17): error CS0119: 'T1' is a type, which is not valid in the given context // if (T1 is object i) Diagnostic(ErrorCode.ERR_BadSKunknown, "T1").WithArguments("CS7.T1", "type").WithLocation(8, 17) ); } [Fact, WorkItem(13316, "https://github.com/dotnet/roslyn/issues/13316")] public void MethodGroupAsExpressionInIsPattern() { var source = @"namespace CS7 { class Program { const int T = 2; static void M(object o) { if (M is T) { } } } }"; CreateCompilation(source).VerifyDiagnostics( // (8,17): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // if (M is T) Diagnostic(ErrorCode.ERR_LambdaInIsAs, "M is T").WithLocation(8, 17) ); } [CompilerTrait(CompilerFeature.IOperation)] [Fact, WorkItem(13383, "https://github.com/dotnet/roslyn/issues/13383")] public void MethodGroupAsExpressionInIsPatternBrokenCode() { var source = @"namespace CS7 { class Program { static void M(object o) { if (o.Equals is()) {} if (object.Equals is()) {} } } }"; var compilation = CreateCompilation(source).VerifyDiagnostics( // (7,17): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // if (o.Equals is()) {} Diagnostic(ErrorCode.ERR_LambdaInIsAs, "o.Equals is()").WithLocation(7, 17), // (8,17): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // if (object.Equals is()) {} Diagnostic(ErrorCode.ERR_LambdaInIsAs, "object.Equals is()").WithLocation(8, 17) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<IsPatternExpressionSyntax>().First(); Assert.Equal("o.Equals is()", node.ToString()); // https://github.com/dotnet/roslyn/issues/27749 : This syntax corresponds to a deconstruction pattern with zero elements, which is not yet supported in IOperation. // compilation.VerifyOperationTree(node, expectedOperationTree: //@" //IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'o.Equals is()') // Expression: // IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'o.Equals is()') // Children(1): // IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'o.Equals') // Children(1): // IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: System.Object, IsInvalid) (Syntax: 'o') // Pattern: //"); } [Fact, WorkItem(13383, "https://github.com/dotnet/roslyn/issues/13383")] public void MethodGroupAsExpressionInIsPatternBrokenCode2() { var source = @"namespace CS7 { class Program { static void M(object o) { if (null is()) {} if ((1, object.Equals) is()) {} } } }"; CreateCompilation(source).VerifyDiagnostics( // (7,17): error CS8117: Invalid operand for pattern match; value required, but found '<null>'. // if (null is()) {} Diagnostic(ErrorCode.ERR_BadPatternExpression, "null").WithArguments("<null>").WithLocation(7, 17), // (8,17): error CS0023: Operator 'is' cannot be applied to operand of type '(int, method group)' // if ((1, object.Equals) is()) {} Diagnostic(ErrorCode.ERR_BadUnaryOp, "(1, object.Equals) is()").WithArguments("is", "(int, method group)").WithLocation(8, 17) ); } [Fact, WorkItem(13723, "https://github.com/dotnet/roslyn/issues/13723")] [CompilerTrait(CompilerFeature.Tuples)] public void ExpressionWithoutAType() { var source = @" public class Vec { public static void Main() { if (null is 1) {} if (Main is 2) {} if (delegate {} is 3) {} if ((1, null) is 4) {} if (null is var x1) {} if (Main is var x2) {} if (delegate {} is var x3) {} if ((1, null) is var x4) {} } } "; CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics( // (6,13): error CS8117: Invalid operand for pattern match; value required, but found '<null>'. // if (null is 1) {} Diagnostic(ErrorCode.ERR_BadPatternExpression, "null").WithArguments("<null>").WithLocation(6, 13), // (7,13): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // if (Main is 2) {} Diagnostic(ErrorCode.ERR_LambdaInIsAs, "Main is 2").WithLocation(7, 13), // (8,13): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // if (delegate {} is 3) {} Diagnostic(ErrorCode.ERR_LambdaInIsAs, "delegate {} is 3").WithLocation(8, 13), // (8,25): warning CS8848: Operator 'is' cannot be used here due to precedence. Use parentheses to disambiguate. // if (delegate {} is 3) {} Diagnostic(ErrorCode.WRN_PrecedenceInversion, "is").WithArguments("is").WithLocation(8, 25), // (9,13): error CS0023: Operator 'is' cannot be applied to operand of type '(int, <null>)' // if ((1, null) is 4) {} Diagnostic(ErrorCode.ERR_BadUnaryOp, "(1, null) is 4").WithArguments("is", "(int, <null>)").WithLocation(9, 13), // (10,13): error CS8117: Invalid operand for pattern match; value required, but found '<null>'. // if (null is var x1) {} Diagnostic(ErrorCode.ERR_BadPatternExpression, "null").WithArguments("<null>").WithLocation(10, 13), // (11,13): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // if (Main is var x2) {} Diagnostic(ErrorCode.ERR_LambdaInIsAs, "Main is var x2").WithLocation(11, 13), // (12,13): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // if (delegate {} is var x3) {} Diagnostic(ErrorCode.ERR_LambdaInIsAs, "delegate {} is var x3").WithLocation(12, 13), // (12,25): warning CS8848: Operator 'is' cannot be used here due to precedence. Use parentheses to disambiguate. // if (delegate {} is var x3) {} Diagnostic(ErrorCode.WRN_PrecedenceInversion, "is").WithArguments("is").WithLocation(12, 25), // (13,13): error CS0023: Operator 'is' cannot be applied to operand of type '(int, <null>)' // if ((1, null) is var x4) {} Diagnostic(ErrorCode.ERR_BadUnaryOp, "(1, null) is var x4").WithArguments("is", "(int, <null>)").WithLocation(13, 13) ); } [Fact, WorkItem(13746, "https://github.com/dotnet/roslyn/issues/13746")] [CompilerTrait(CompilerFeature.Tuples)] public void ExpressionWithoutAType02() { var source = @" public class Program { public static void Main() { if ((1, null) is Program) {} } } "; CreateCompilation(source, options: TestOptions.DebugExe).VerifyDiagnostics( // (6,13): error CS0023: Operator 'is' cannot be applied to operand of type '(int, <null>)' // if ((1, null) is Program) {} Diagnostic(ErrorCode.ERR_BadUnaryOp, "(1, null) is Program").WithArguments("is", "(int, <null>)").WithLocation(6, 13) ); } [Fact, WorkItem(15956, "https://github.com/dotnet/roslyn/issues/15956")] public void ThrowExpressionWithNullableDecimal() { var source = @" using System; public class ITest { public decimal Test() => 1m; } public class TestClass { public void Test(ITest test) { var result = test?.Test() ?? throw new Exception(); } }"; // DEBUG var compilation = CreateCompilation(source, options: TestOptions.DebugDll); compilation.VerifyDiagnostics(); compilation.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(compilation); verifier.VerifyIL("TestClass.Test", @"{ // Code size 18 (0x12) .maxstack 1 .locals init (decimal V_0, //result decimal V_1) IL_0000: nop IL_0001: ldarg.1 IL_0002: brtrue.s IL_000a IL_0004: newobj ""System.Exception..ctor()"" IL_0009: throw IL_000a: ldarg.1 IL_000b: call ""decimal ITest.Test()"" IL_0010: stloc.0 IL_0011: ret }"); // RELEASE compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); compilation.VerifyEmitDiagnostics(); verifier = CompileAndVerify(compilation); verifier.VerifyIL("TestClass.Test", @"{ // Code size 17 (0x11) .maxstack 1 IL_0000: ldarg.1 IL_0001: brtrue.s IL_0009 IL_0003: newobj ""System.Exception..ctor()"" IL_0008: throw IL_0009: ldarg.1 IL_000a: call ""decimal ITest.Test()"" IL_000f: pop IL_0010: ret }"); } [Fact, WorkItem(15956, "https://github.com/dotnet/roslyn/issues/15956")] public void ThrowExpressionWithNullableDateTime() { var source = @" using System; public class ITest { public DateTime Test() => new DateTime(2008, 5, 1, 8, 30, 52); } public class TestClass { public void Test(ITest test) { var result = test?.Test() ?? throw new Exception(); } }"; // DEBUG var compilation = CreateCompilation(source, options: TestOptions.DebugDll); compilation.VerifyDiagnostics(); compilation.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(compilation); verifier.VerifyIL("TestClass.Test", @"{ // Code size 18 (0x12) .maxstack 1 .locals init (System.DateTime V_0, //result System.DateTime V_1) IL_0000: nop IL_0001: ldarg.1 IL_0002: brtrue.s IL_000a IL_0004: newobj ""System.Exception..ctor()"" IL_0009: throw IL_000a: ldarg.1 IL_000b: call ""System.DateTime ITest.Test()"" IL_0010: stloc.0 IL_0011: ret }"); // RELEASE compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); compilation.VerifyEmitDiagnostics(); verifier = CompileAndVerify(compilation); verifier.VerifyIL("TestClass.Test", @"{ // Code size 17 (0x11) .maxstack 1 IL_0000: ldarg.1 IL_0001: brtrue.s IL_0009 IL_0003: newobj ""System.Exception..ctor()"" IL_0008: throw IL_0009: ldarg.1 IL_000a: call ""System.DateTime ITest.Test()"" IL_000f: pop IL_0010: ret }"); } [Fact] public void ThrowExpressionForParameterValidation() { var source = @"using System; class Program { public static void Main(string[] args) { foreach (var s in new[] { ""0123"", ""goo"" }) { Console.Write(s + "" ""); try { Console.WriteLine(Ver(s)); } catch (ArgumentException) { Console.WriteLine(""throws""); } } } static int Ver(string s) { var result = int.TryParse(s, out int k) ? k : throw new ArgumentException(nameof(s)); return k; // definitely assigned! } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"0123 123 goo throws"); } [Fact] public void ThrowExpressionWithNullable01() { var source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine(M(1)); try { Console.WriteLine(M(null)); } catch (Exception) { Console.WriteLine(""thrown""); } } static int M(int? data) { return data ?? throw null; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"1 thrown"); } [Fact] public void ThrowExpressionWithNullable02() { var source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine(M(1)); try { Console.WriteLine(M(null)); } catch (Exception) { Console.WriteLine(""thrown""); } } static string M(object data) { return data?.ToString() ?? throw null; } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"1 thrown"); } [Fact] public void ThrowExpressionWithNullable03() { var source = @"using System; using System.Threading.Tasks; class Program { public static void Main(string[] args) { MainAsync().Wait(); } static async Task MainAsync() { foreach (var i in new[] { 1, 2 }) { try { var used = (await Goo(i))?.ToString() ?? throw await Bar(i); } catch (Exception ex) { Console.WriteLine(""thrown "" + ex.Message); } } } static async Task<object> Goo(int i) { await Task.Yield(); return (i == 1) ? i : (object)null; } static async Task<Exception> Bar(int i) { await Task.Yield(); Console.WriteLine(""making exception "" + i); return new Exception(i.ToString()); } } "; var compilation = CreateEmptyCompilation(source, options: TestOptions.DebugExe, references: new[] { MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929 }); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"making exception 2 thrown 2"); } [Fact] public void ThrowExpressionPrecedence01() { var source = @"using System; class Program { public static void Main(string[] args) { Exception ex = null; try { // The ?? operator is right-associative, even under 'throw' ex = ex ?? throw ex ?? throw new ArgumentException(""blue""); } catch (ArgumentException x) { Console.WriteLine(x.Message); } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"blue"); } [Fact] public void ThrowExpressionPrecedence02() { var source = @"using System; class Program { public static void Main(string[] args) { MyException ex = null; try { // Throw expression binds looser than + ex = ex ?? throw ex + 1; } catch (MyException x) { Console.WriteLine(x.Message); } } } class MyException : Exception { public MyException(string message) : base(message) {} public static MyException operator +(MyException left, int right) { return new MyException(""green""); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"green"); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void IsPatternPrecedence() { var source = @"using System; class Program { const bool B = true; const int One = 1; public static void Main(string[] args) { object a = null; B c = null; Console.WriteLine(a is B & c); // prints 5 (correct) Console.WriteLine(a is B > c); // prints 6 (correct) Console.WriteLine(a is B < c); // was syntax error but should print 7 Console.WriteLine(3 is One + 2); // should print True Console.WriteLine(One + 2 is 3); // should print True } } class B { public static int operator &(bool left, B right) => 5; public static int operator >(bool left, B right) => 6; public static int operator <(bool left, B right) => 7; public static int operator +(bool left, B right) => 8; } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular6).VerifyDiagnostics( // (15,27): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // Console.WriteLine(3 is One + 2); // should print True Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "3 is One + 2").WithArguments("pattern matching", "7.0").WithLocation(15, 27), // (16,27): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // Console.WriteLine(One + 2 is 3); // should print True Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "One + 2 is 3").WithArguments("pattern matching", "7.0").WithLocation(16, 27), // (15,27): warning CS8417: The given expression always matches the provided constant. // Console.WriteLine(3 is One + 2); // should print True Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesConstant, "3 is One + 2").WithLocation(15, 27), // (16,27): warning CS8417: The given expression always matches the provided constant. // Console.WriteLine(One + 2 is 3); // should print True Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesConstant, "One + 2 is 3").WithLocation(16, 27) ); var expectedOutput = @"5 6 7 True True"; compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (15,27): warning CS8417: The given expression always matches the provided constant. // Console.WriteLine(3 is One + 2); // should print True Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesConstant, "3 is One + 2").WithLocation(15, 27), // (16,27): warning CS8417: The given expression always matches the provided constant. // Console.WriteLine(One + 2 is 3); // should print True Diagnostic(ErrorCode.WRN_GivenExpressionAlwaysMatchesConstant, "One + 2 is 3").WithLocation(16, 27) ); var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void IsPatternPrecedence02() { var source = @"using System; class Program { public static void Main(string[] args) { foreach (object A in new[] { null, new B<C,D>() }) { // pass one argument, a pattern-matching operation M(A is B < C, D > E); switch (A) { case B < C, D > F: Console.WriteLine(""yes""); break; default: Console.WriteLine(""no""); break; } } } static void M(object o) { Console.WriteLine(o); } } class B<C,D> { } class C {} class D {} "; var expectedOutput = @"False no True yes"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void IsPatternPrecedence03() { var source = @"using System; class Program { public static void Main(string[] args) { object A = new B<C, D>(); Console.WriteLine(A is B < C, D > E); Console.WriteLine(A as B < C, D > ?? string.Empty); } } class B<C,D> { public static implicit operator string(B<C,D> b) => nameof(B<C,D>); } class C {} class D {} "; var expectedOutput = @"True B"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); SyntaxFactory.ParseExpression("A is B < C, D > E").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("A as B < C, D > E").GetDiagnostics().Verify( // (1,1): error CS1073: Unexpected token 'E' // A as B < C, D > E Diagnostic(ErrorCode.ERR_UnexpectedToken, "A as B < C, D >").WithArguments("E").WithLocation(1, 1) ); SyntaxFactory.ParseExpression("A as B < C, D > ?? string.Empty").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("A is B < C, D > ?? string.Empty").GetDiagnostics().Verify( // (1,1): error CS1073: Unexpected token ',' // A is B < C, D > ?? string.Empty Diagnostic(ErrorCode.ERR_UnexpectedToken, "A is B < C").WithArguments(",").WithLocation(1, 1) ); } [Fact, WorkItem(14636, "https://github.com/dotnet/roslyn/issues/14636")] public void NameofPattern() { var source = @"using System; class Program { public static void Main(string[] args) { M(""a""); M(""b""); M(null); M(new nameof()); } public static void M(object a) { Console.WriteLine(a is nameof(a)); Console.WriteLine(a is nameof); } } class nameof { } "; var expectedOutput = @"True False False False False False False True"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact, WorkItem(14825, "https://github.com/dotnet/roslyn/issues/14825")] public void PatternVarDeclaredInReceiverUsedInArgument() { var source = @"using System.Linq; public class C { public string[] Goo2(out string x) { x = """"; return null; } public string[] Goo3(bool b) { return null; } public string[] Goo5(string u) { return null; } public void Test() { var t1 = Goo2(out var x1).Concat(Goo5(x1)); var t2 = Goo3(t1 is var x2).Concat(Goo5(x2.First())); } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x2Decl = GetPatternDeclarations(tree, "x2").Single(); var x2Ref = GetReferences(tree, "x2").Single(); VerifyModelForDeclarationOrVarSimplePattern(model, x2Decl, x2Ref); Assert.Equal("System.Collections.Generic.IEnumerable<System.String>", model.GetTypeInfo(x2Ref).Type.ToTestDisplayString()); } [Fact] public void DiscardInPattern() { var source = @" using static System.Console; public class C { public static void Main() { int i = 3; Write($""is int _: {i is int _}, ""); Write($""is var _: {i is var _}, ""); switch (3) { case int _: Write(""case int _, ""); break; } switch (3L) { case var _: Write(""case var _""); break; } } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); CompileAndVerify(compilation, expectedOutput: "is int _: True, is var _: True, case int _, case var _"); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var discard1 = GetDiscardDesignations(tree).First(); Assert.Null(model.GetDeclaredSymbol(discard1)); var declaration1 = (DeclarationPatternSyntax)discard1.Parent; Assert.Equal("int _", declaration1.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration1).Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration1.Type).Type.ToTestDisplayString()); var discard2 = GetDiscardDesignations(tree).Skip(1).First(); Assert.Null(model.GetDeclaredSymbol(discard2)); Assert.Null(model.GetSymbolInfo(discard2).Symbol); var declaration2 = (VarPatternSyntax)discard2.Parent; Assert.Equal("var _", declaration2.ToString()); Assert.Null(model.GetSymbolInfo(declaration2).Symbol); var discard3 = GetDiscardDesignations(tree).Skip(2).First(); Assert.Null(model.GetDeclaredSymbol(discard3)); var declaration3 = (DeclarationPatternSyntax)discard3.Parent; Assert.Equal("int _", declaration3.ToString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration3).Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetTypeInfo(declaration3.Type).Type.ToTestDisplayString()); var discard4 = GetDiscardDesignations(tree).Skip(3).First(); Assert.Null(model.GetDeclaredSymbol(discard4)); var declaration4 = (VarPatternSyntax)discard4.Parent; Assert.Equal("var _", declaration4.ToString()); } [Fact] public void ShortDiscardInPattern() { var source = @" using static System.Console; public class C { public static void Main() { int i = 3; Write($""is _: {i is _}, ""); switch (3) { case _: Write(""case _""); break; } } } "; CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (8,29): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?) // Write($"is _: {i is _}, "); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(8, 29), // (11,18): error CS0103: The name '_' does not exist in the current context // case _: Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(11, 18) ); CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (8,29): error CS0246: The type or namespace name '_' could not be found (are you missing a using directive or an assembly reference?) // Write($"is _: {i is _}, "); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "_").WithArguments("_").WithLocation(8, 29), // (11,18): error CS0103: The name '_' does not exist in the current context // case _: Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(11, 18) ); } [Fact] public void UnderscoreInPattern2() { var source = @" using static System.Console; public class C { public static void Main() { int i = 3; int _ = 4; Write($""is _: {i is _}, ""); switch (3) { case _: Write(""case _""); break; } } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); compilation.VerifyDiagnostics( // (9,29): error CS0118: '_' is a variable but is used like a type // Write($"is _: {i is _}, "); Diagnostic(ErrorCode.ERR_BadSKknown, "_").WithArguments("_", "variable", "type").WithLocation(9, 29), // (12,18): error CS0150: A constant value is expected // case _: Diagnostic(ErrorCode.ERR_ConstantExpected, "_").WithLocation(12, 18) ); } [Fact] public void UnderscoreInPattern() { var source = @" using static System.Console; public class C { public static void Main() { int i = 3; if (i is int _) { Write(_); } if (i is var _) { Write(_); } switch (3) { case int _: Write(_); break; } switch (3) { case var _: Write(_); break; } } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (8,33): error CS0103: The name '_' does not exist in the current context // if (i is int _) { Write(_); } Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(8, 33), // (9,33): error CS0103: The name '_' does not exist in the current context // if (i is var _) { Write(_); } Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(9, 33), // (13,23): error CS0103: The name '_' does not exist in the current context // Write(_); Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(13, 23), // (19,23): error CS0103: The name '_' does not exist in the current context // Write(_); Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(19, 23) ); } [Fact] public void PointerTypeInPattern() { // pointer types are not supported in patterns. Therefore an attempt to use // a pointer type will be interpreted by the parser as a multiplication // (i.e. an expression that is a constant pattern rather than a declaration // pattern) var source = @" public class var {} unsafe public class Typ { public static void Main(int* a, var* c, Typ* e) { { if (a is int* b) {} if (c is var* d) {} if (e is Typ* f) {} } { switch (a) { case int* b: break; } switch (c) { case var* d: break; } switch (e) { case Typ* f: break; } } } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeDebugDll); compilation.VerifyDiagnostics( // (8,22): error CS1525: Invalid expression term 'int' // if (a is int* b) {} Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(8, 22), // (13,31): error CS1525: Invalid expression term 'int' // switch (a) { case int* b: break; } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(13, 31), // (5,42): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('var') // public static void Main(int* a, var* c, Typ* e) Diagnostic(ErrorCode.ERR_ManagedAddr, "c").WithArguments("var").WithLocation(5, 42), // (5,50): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('Typ') // public static void Main(int* a, var* c, Typ* e) Diagnostic(ErrorCode.ERR_ManagedAddr, "e").WithArguments("Typ").WithLocation(5, 50), // (8,27): error CS0103: The name 'b' does not exist in the current context // if (a is int* b) {} Diagnostic(ErrorCode.ERR_NameNotInContext, "b").WithArguments("b").WithLocation(8, 27), // (9,22): error CS0119: 'var' is a type, which is not valid in the given context // if (c is var* d) {} Diagnostic(ErrorCode.ERR_BadSKunknown, "var").WithArguments("var", "type").WithLocation(9, 22), // (9,27): error CS0103: The name 'd' does not exist in the current context // if (c is var* d) {} Diagnostic(ErrorCode.ERR_NameNotInContext, "d").WithArguments("d").WithLocation(9, 27), // (10,22): error CS0119: 'Typ' is a type, which is not valid in the given context // if (e is Typ* f) {} Diagnostic(ErrorCode.ERR_BadSKunknown, "Typ").WithArguments("Typ", "type").WithLocation(10, 22), // (10,27): error CS0103: The name 'f' does not exist in the current context // if (e is Typ* f) {} Diagnostic(ErrorCode.ERR_NameNotInContext, "f").WithArguments("f").WithLocation(10, 27), // (13,36): error CS0103: The name 'b' does not exist in the current context // switch (a) { case int* b: break; } Diagnostic(ErrorCode.ERR_NameNotInContext, "b").WithArguments("b").WithLocation(13, 36), // (14,31): error CS0119: 'var' is a type, which is not valid in the given context // switch (c) { case var* d: break; } Diagnostic(ErrorCode.ERR_BadSKunknown, "var").WithArguments("var", "type").WithLocation(14, 31), // (14,36): error CS0103: The name 'd' does not exist in the current context // switch (c) { case var* d: break; } Diagnostic(ErrorCode.ERR_NameNotInContext, "d").WithArguments("d").WithLocation(14, 36), // (15,31): error CS0119: 'Typ' is a type, which is not valid in the given context // switch (e) { case Typ* f: break; } Diagnostic(ErrorCode.ERR_BadSKunknown, "Typ").WithArguments("Typ", "type").WithLocation(15, 31), // (15,36): error CS0103: The name 'f' does not exist in the current context // switch (e) { case Typ* f: break; } Diagnostic(ErrorCode.ERR_NameNotInContext, "f").WithArguments("f").WithLocation(15, 36) ); } [Fact] [WorkItem(16513, "https://github.com/dotnet/roslyn/issues/16513")] public void OrderOfPatternOperands() { var source = @" using System; class Program { public static void Main(string[] args) { object c = new C(); Console.WriteLine(c is 3); c = 2; Console.WriteLine(c is 3); c = 3; Console.WriteLine(c is 3); } } class C { override public bool Equals(object other) { return other is int x; } override public int GetHashCode() => 0; } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var comp = CompileAndVerify(compilation, expectedOutput: @"False False True"); } [Fact] public void MultiplyInPattern() { // pointer types are not supported in patterns. Therefore an attempt to use // a pointer type will be interpreted by the parser as a multiplication // (i.e. an expression that is a constant pattern rather than a declaration // pattern) var source = @" public class Program { public static void Main() { const int two = 2; const int three = 3; int six = two * three; System.Console.WriteLine(six is two * three); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var comp = CompileAndVerify(compilation, expectedOutput: "True"); } [Fact] public void ColorColorConstantPattern() { var source = @" public class Program { public static Color Color { get; } public static void M(object o) { System.Console.WriteLine(o is Color.Constant); } public static void Main() { M(Color.Constant); } } public class Color { public const string Constant = ""abc""; } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); var comp = CompileAndVerify(compilation, expectedOutput: "True"); } [Fact] [WorkItem(336030, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/336030")] public void NullOperand() { var source = @" class C { void M() { System.Console.Write(null is Missing x); System.Console.Write(null is Missing); switch(null) { case Missing: case Missing y: break; } } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,30): error CS8117: Invalid operand for pattern match; value required, but found '<null>'. // System.Console.Write(null is Missing x); Diagnostic(ErrorCode.ERR_BadPatternExpression, "null").WithArguments("<null>").WithLocation(6, 30), // (6,38): error CS0246: The type or namespace name 'Missing' could not be found (are you missing a using directive or an assembly reference?) // System.Console.Write(null is Missing x); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Missing").WithArguments("Missing").WithLocation(6, 38), // (7,38): error CS0246: The type or namespace name 'Missing' could not be found (are you missing a using directive or an assembly reference?) // System.Console.Write(null is Missing); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Missing").WithArguments("Missing").WithLocation(7, 38), // (8,16): error CS8119: The switch expression must be a value; found '<null>'. // switch(null) Diagnostic(ErrorCode.ERR_SwitchExpressionValueExpected, "null").WithArguments("<null>").WithLocation(8, 16), // (10,18): error CS0103: The name 'Missing' does not exist in the current context // case Missing: Diagnostic(ErrorCode.ERR_NameNotInContext, "Missing").WithArguments("Missing").WithLocation(10, 18), // (11,18): error CS0246: The type or namespace name 'Missing' could not be found (are you missing a using directive or an assembly reference?) // case Missing y: Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Missing").WithArguments("Missing").WithLocation(11, 18) ); } [Fact] [WorkItem(336030, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=336030")] [WorkItem(294570, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=294570")] public void Fuzz46() { var program = @" public class Program46 { public static void Main(string[] args) { switch ((() => 1)) { case int x4: case string x9: case M: case ((int)M()): break; } } private static object M() => null; }"; CreateCompilation(program).VerifyDiagnostics( // (6,17): error CS8119: The switch expression must be a value; found 'lambda expression'. // switch ((() => 1)) Diagnostic(ErrorCode.ERR_SwitchExpressionValueExpected, "(() => 1)").WithArguments("lambda expression").WithLocation(6, 17), // (10,18): error CS0150: A constant value is expected // case M: Diagnostic(ErrorCode.ERR_ConstantExpected, "M").WithLocation(10, 18), // (11,19): error CS0150: A constant value is expected // case ((int)M()): Diagnostic(ErrorCode.ERR_ConstantExpected, "(int)M()").WithLocation(11, 19) ); } [Fact] [WorkItem(363714, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=363714")] public void Fuzz46b() { var program = @" public class Program46 { public static void Main(string[] args) { switch ((() => 1)) { case M: break; } } private static object M() => null; }"; CreateCompilation(program).VerifyDiagnostics( // (6,17): error CS8119: The switch expression must be a value; found 'lambda expression'. // switch ((() => 1)) Diagnostic(ErrorCode.ERR_SwitchExpressionValueExpected, "(() => 1)").WithArguments("lambda expression").WithLocation(6, 17), // (8,18): error CS0150: A constant value is expected // case M: Diagnostic(ErrorCode.ERR_ConstantExpected, "M").WithLocation(8, 18) ); } [Fact] [WorkItem(336030, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=336030")] public void Fuzz401() { var program = @" public class Program401 { public static void Main(string[] args) { if (null is M) {} } private static object M() => null; }"; CreateCompilation(program).VerifyDiagnostics( // (6,13): error CS8117: Invalid operand for pattern match; value required, but found '<null>'. // if (null is M) {} Diagnostic(ErrorCode.ERR_BadPatternExpression, "null").WithArguments("<null>").WithLocation(6, 13), // (6,21): error CS0150: A constant value is expected // if (null is M) {} Diagnostic(ErrorCode.ERR_ConstantExpected, "M").WithLocation(6, 21) ); } [Fact] [WorkItem(364165, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=364165")] [WorkItem(16296, "https://github.com/dotnet/roslyn/issues/16296")] public void Fuzz1717() { var program = @" public class Program1717 { public static void Main(string[] args) { switch (default(int?)) { case 2: break; case double.NaN: break; case var x9: case string _: break; } } private static object M() => null; }"; CreateCompilation(program).VerifyDiagnostics( // (10,18): error CS0266: Cannot implicitly convert type 'double' to 'int?'. An explicit conversion exists (are you missing a cast?) // case double.NaN: Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "double.NaN").WithArguments("double", "int?").WithLocation(10, 18), // (13,18): error CS8121: An expression of type 'int?' cannot be handled by a pattern of type 'string'. // case string _: Diagnostic(ErrorCode.ERR_PatternWrongType, "string").WithArguments("int?", "string").WithLocation(13, 18) ); } [Fact, WorkItem(16559, "https://github.com/dotnet/roslyn/issues/16559")] public void CasePatternVariableUsedInCaseExpression() { var program = @" public class Program5815 { public static void Main(object o) { switch (o) { case Color Color: case Color? Color2: break; } } private static object M() => null; }"; var compilation = CreateCompilation(program).VerifyDiagnostics( // (9,32): error CS1525: Invalid expression term 'break' // case Color? Color2: Diagnostic(ErrorCode.ERR_InvalidExprTerm, "").WithArguments("break").WithLocation(9, 32), // (9,32): error CS1003: Syntax error, ':' expected // case Color? Color2: Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(":", "break").WithLocation(9, 32), // (8,18): error CS0118: 'Color' is a variable but is used like a type // case Color Color: Diagnostic(ErrorCode.ERR_BadSKknown, "Color").WithArguments("Color", "variable", "type").WithLocation(8, 18), // (9,25): error CS0103: The name 'Color2' does not exist in the current context // case Color? Color2: Diagnostic(ErrorCode.ERR_NameNotInContext, "Color2").WithArguments("Color2").WithLocation(9, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var colorDecl = GetPatternDeclarations(tree, "Color").ToArray(); var colorRef = GetReferences(tree, "Color").ToArray(); Assert.Equal(1, colorDecl.Length); Assert.Equal(2, colorRef.Length); Assert.Null(model.GetSymbolInfo(colorRef[0]).Symbol); VerifyModelForDeclarationOrVarSimplePattern(model, colorDecl[0], colorRef[1]); } [Fact, WorkItem(16559, "https://github.com/dotnet/roslyn/issues/16559")] public void Fuzz5815() { var program = @" public class Program5815 { public static void Main(string[] args) { switch ((int)M()) { case var x3: case true ? x3 : 4: break; } } private static object M() => null; }"; var compilation = CreateCompilation(program).VerifyDiagnostics( // (9,18): error CS0150: A constant value is expected // case true ? x3 : 4: Diagnostic(ErrorCode.ERR_ConstantExpected, "true ? x3 : 4").WithLocation(9, 18), // (9,25): error CS0165: Use of unassigned local variable 'x3' // case true ? x3 : 4: Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(9, 25) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var x3Decl = GetPatternDeclarations(tree, "x3").ToArray(); var x3Ref = GetReferences(tree, "x3").ToArray(); Assert.Equal(1, x3Decl.Length); Assert.Equal(1, x3Ref.Length); VerifyModelForDeclarationOrVarSimplePattern(model, x3Decl[0], x3Ref); } [Fact] public void Fuzz_Conjunction_01() { var program = @" public class Program { public static void Main(string[] args) { if (((int?)1) is {} and 1) { } } }"; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( ); } [Fact] public void Fuzz_738490379() { var program = @" public class Program738490379 { public static void Main(string[] args) { if (NotFound is var (M, not int _ or NotFound _) { }) {} } private static object M() => null; }"; var compilation = CreateCompilation(program, parseOptions: TestOptions.RegularWithPatternCombinators).VerifyDiagnostics( // (6,13): error CS0841: Cannot use local variable 'NotFound' before it is declared // if (NotFound is var (M, not int _ or NotFound _) { }) {} Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "NotFound").WithArguments("NotFound").WithLocation(6, 13), // (6,37): error CS1026: ) expected // if (NotFound is var (M, not int _ or NotFound _) { }) {} Diagnostic(ErrorCode.ERR_CloseParenExpected, "int").WithLocation(6, 37), // (6,37): error CS1026: ) expected // if (NotFound is var (M, not int _ or NotFound _) { }) {} Diagnostic(ErrorCode.ERR_CloseParenExpected, "int").WithLocation(6, 37), // (6,37): error CS1023: Embedded statement cannot be a declaration or labeled statement // if (NotFound is var (M, not int _ or NotFound _) { }) {} Diagnostic(ErrorCode.ERR_BadEmbeddedStmt, "int _ ").WithLocation(6, 37), // (6,41): warning CS0168: The variable '_' is declared but never used // if (NotFound is var (M, not int _ or NotFound _) { }) {} Diagnostic(ErrorCode.WRN_UnreferencedVar, "_").WithArguments("_").WithLocation(6, 41), // (6,43): error CS1002: ; expected // if (NotFound is var (M, not int _ or NotFound _) { }) {} Diagnostic(ErrorCode.ERR_SemicolonExpected, "or").WithLocation(6, 43), // (6,43): error CS0246: The type or namespace name 'or' could not be found (are you missing a using directive or an assembly reference?) // if (NotFound is var (M, not int _ or NotFound _) { }) {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "or").WithArguments("or").WithLocation(6, 43), // (6,55): error CS1002: ; expected // if (NotFound is var (M, not int _ or NotFound _) { }) {} Diagnostic(ErrorCode.ERR_SemicolonExpected, "_").WithLocation(6, 55), // (6,55): error CS0103: The name '_' does not exist in the current context // if (NotFound is var (M, not int _ or NotFound _) { }) {} Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(6, 55), // (6,56): error CS1002: ; expected // if (NotFound is var (M, not int _ or NotFound _) { }) {} Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(6, 56), // (6,56): error CS1513: } expected // if (NotFound is var (M, not int _ or NotFound _) { }) {} Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(6, 56), // (6,62): error CS1513: } expected // if (NotFound is var (M, not int _ or NotFound _) { }) {} Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(6, 62) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/16721")] public void Fuzz() { const int numTests = 1200000; int dt = (int)Math.Abs(DateTime.Now.Ticks % 1000000000); for (int i = 1; i < numTests; i++) { PatternMatchingFuzz(i + dt); } } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/16721")] public void MultiFuzz() { // Just like Fuzz(), but take advantage of concurrency on the test host. const int numTasks = 300; const int numTestsPerTask = 4000; int dt = (int)Math.Abs(DateTime.Now.Ticks % 1000000000); var tasks = Enumerable.Range(0, numTasks).Select(t => Task.Run(() => { int k = dt + t * numTestsPerTask; for (int i = 1; i < numTestsPerTask; i++) { PatternMatchingFuzz(i + k); } })); Task.WaitAll(tasks.ToArray()); } private static void PatternMatchingFuzz(int dt) { Random r = new Random(dt); // generate a pattern-matching switch randomly from templates string[] expressions = new[] { "M", // a method group "(() => 1)", // a lambda expression "1", // a constant "2", // a constant "null", // the null constant "default(int?)", // a null constant of type int? "((int?)1)", // a constant of type int? "M()", // a method invocation "double.NaN", // a scary constant "1.1", // a double constant "NotFound" // an unbindable expression }; string Expression() { int index = r.Next(expressions.Length + 1) - 1; return (index < 0) ? $"(({Type()})M())" : expressions[index]; } string[] types = new[] { "object", "var", "int", "int?", "double", "string", "NotFound" }; string Type() => types[r.Next(types.Length)]; string Pattern(int d = 5) { switch (r.Next(d <= 1 ? 9 : 12)) { default: return Expression(); // a "constant" pattern case 3: case 4: return Type(); case 5: return Type() + " _"; case 6: return Type() + " x" + r.Next(10); case 7: return "not " + Pattern(d - 1); case 8: return "(" + Pattern(d - 1) + ")"; case 9: return makeRecursivePattern(d); case 10: return Pattern(d - 1) + " and " + Pattern(d - 1); case 11: return Pattern(d - 1) + " or " + Pattern(d - 1); } string makeRecursivePattern(int d) { while (true) { bool haveParens = r.Next(2) == 0; bool haveCurlies = r.Next(2) == 0; if (!haveParens && !haveCurlies) continue; bool haveType = r.Next(2) == 0; bool haveIdentifier = r.Next(2) == 0; return $"{(haveType ? Type() : null)} {(haveParens ? $"({makePatternList(d - 1, false)})" : null)} {(haveCurlies ? $"{"{ "}{makePatternList(d - 1, true)}{" }"}" : null)} {(haveIdentifier ? " x" + r.Next(10) : null)}"; } } string makePatternList(int d, bool propNames) { return string.Join(", ", Enumerable.Range(0, r.Next(3)).Select(i => $"{(propNames ? $"P{r.Next(10)}: " : null)}{Pattern(d)}")); } } string body = @" public class Program{0} {{ public static void Main(string[] args) {{ {1} }} private static object M() => null; }}"; var statement = new StringBuilder(); switch (r.Next(2)) { case 0: // test the "is-pattern" expression statement.Append($"if ({Expression()} is {Pattern()}) {{}}"); break; case 1: // test the pattern switch statement statement.AppendLine($"switch ({Expression()})"); statement.AppendLine("{"); var nCases = r.Next(5); for (int i = 1; i <= nCases; i++) { statement.AppendLine($" case {Pattern()}:"); if (i == nCases || r.Next(2) == 0) { statement.AppendLine($" break;"); } } statement.AppendLine("}"); break; default: throw null; } var program = string.Format(body, dt, statement); CreateCompilation(program).GetDiagnostics(); } [Fact, WorkItem(16671, "https://github.com/dotnet/roslyn/issues/16671")] public void TypeParameterSubsumption01() { var program = @" using System; public class Program { public static void Main(string[] args) { PatternMatching<Base, Derived>(new Base()); PatternMatching<Base, Derived>(new Derived()); PatternMatching<Base, Derived>(null); PatternMatching<object, int>(new object()); PatternMatching<object, int>(2); PatternMatching<object, int>(null); PatternMatching<object, int?>(new object()); PatternMatching<object, int?>(2); PatternMatching<object, int?>(null); } static void PatternMatching<TBase, TDerived>(TBase o) where TDerived : TBase { switch (o) { case TDerived td: Console.WriteLine(nameof(TDerived)); break; case TBase tb: Console.WriteLine(nameof(TBase)); break; default: Console.WriteLine(""Neither""); break; } } } class Base { } class Derived : Base { } "; var compilation = CreateCompilation(program, options: TestOptions.DebugExe).VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"TBase TDerived Neither TBase TDerived Neither TBase TDerived Neither"); } [Fact, WorkItem(16671, "https://github.com/dotnet/roslyn/issues/16671")] public void TypeParameterSubsumption02() { var program = @" using System; public class Program { static void PatternMatching<TBase, TDerived>(TBase o) where TDerived : TBase { switch (o) { case TBase tb: Console.WriteLine(nameof(TBase)); break; case TDerived td: Console.WriteLine(nameof(TDerived)); break; default: Console.WriteLine(""Neither""); break; } } } class Base { } class Derived : Base { } "; var compilation = CreateCompilation(program).VerifyDiagnostics( // (12,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match. // case TDerived td: Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "TDerived td").WithLocation(12, 18) ); } [Fact, WorkItem(16688, "https://github.com/dotnet/roslyn/issues/16688")] public void TypeParameterSubsumption03() { var program = @" using System.Collections.Generic; public class Program { private static void Pattern<T>(T thing) where T : class { switch (thing) { case T tThing: break; case IEnumerable<object> s: break; } } } "; var compilation = CreateCompilation(program).VerifyDiagnostics( // (11,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match. // case IEnumerable<object> s: Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "IEnumerable<object> s").WithLocation(11, 18) ); } [Fact, WorkItem(16696, "https://github.com/dotnet/roslyn/issues/16696")] public void TypeParameterSubsumption04() { var program = @" using System; using System.Collections.Generic; public class Program { private static int Pattern1<TBase, TDerived>(object thing) where TBase : class where TDerived : TBase { switch (thing) { case IEnumerable<TBase> sequence: return 1; // IEnumerable<TBase> does not subsume IEnumerable<TDerived> because TDerived may be a value type. case IEnumerable<TDerived> derivedSequence: return 2; default: return 3; } } private static int Pattern2<TBase, TDerived>(object thing) where TBase : class where TDerived : TBase { switch (thing) { case IEnumerable<object> s: return 1; // IEnumerable<object> does not subsume IEnumerable<TDerived> because TDerived may be a value type. case IEnumerable<TDerived> derivedSequence: return 2; default: return 3; } } public static void Main(string[] args) { Console.WriteLine(Pattern1<object, int>(new List<object>())); Console.WriteLine(Pattern1<object, int>(new List<int>())); Console.WriteLine(Pattern1<object, int>(null)); Console.WriteLine(Pattern2<object, int>(new List<object>())); Console.WriteLine(Pattern2<object, int>(new List<int>())); Console.WriteLine(Pattern2<object, int>(null)); } } "; var compilation = CreateCompilation(program, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"1 2 3 1 2 3"); } [Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")] public void TypeParameterSubsumption05() { var program = @" public class Program { static void M<T, U>(T t, U u) where T : U { switch(""test"") { case U uu: break; case T tt: // Produces a diagnostic about subsumption/unreachability break; } } } "; CreateCompilation(program, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7).VerifyDiagnostics( // (8,18): error CS8314: An expression of type 'string' cannot be handled by a pattern of type 'U' in C# 7.0. Please use language version 7.1 or greater. // case U uu: Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "U").WithArguments("string", "U", "7.0", "7.1").WithLocation(8, 18), // (10,18): error CS8314: An expression of type 'string' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater. // case T tt: // Produces a diagnostic about subsumption/unreachability Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("string", "T", "7.0", "7.1").WithLocation(10, 18) ); CreateCompilation(program, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7_1).VerifyDiagnostics( // (10,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match. // case T tt: // Produces a diagnostic about subsumption/unreachability Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "T tt").WithLocation(10, 18) ); } [Fact, WorkItem(17103, "https://github.com/dotnet/roslyn/issues/17103")] public void IsConstantPatternConversion_Positive() { var source = @"using System; public class Program { public static void Main() { { byte b = 12; Console.WriteLine(b is 12); // True Console.WriteLine(b is 13); // False Console.WriteLine(b is (int)12L); // True Console.WriteLine(b is (int)13L); // False } bool Is42(byte b) => b is 42; Console.WriteLine(Is42(42)); Console.WriteLine(Is42(43)); Console.WriteLine(Is42((int)42L)); Console.WriteLine(Is42((int)43L)); } }"; var expectedOutput = @"True False True False True False True False"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact, WorkItem(17103, "https://github.com/dotnet/roslyn/issues/17103")] public void IsConstantPatternConversion_Negative() { var source = @"using System; public class Program { public static void Main() { byte b = 12; Console.WriteLine(b is 12L); Console.WriteLine(1 is null); } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (7,32): error CS0266: Cannot implicitly convert type 'long' to 'byte'. An explicit conversion exists (are you missing a cast?) // Console.WriteLine(b is 12L); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "12L").WithArguments("long", "byte").WithLocation(7, 32), // (8,32): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // Console.WriteLine(1 is null); Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(8, 32) ); } [Fact] [WorkItem(9542, "https://github.com/dotnet/roslyn/issues/9542")] [WorkItem(16876, "https://github.com/dotnet/roslyn/issues/16876")] public void DecisionTreeCoverage_Positive() { // tests added to complete coverage of the decision tree and pattern-matching implementation var source = @"using System; public class X { public static void Main() { void M1(int i, bool b) { switch (i) { case 1 when b: Console.WriteLine(""M1a""); break; case 1: Console.WriteLine(""M1b""); break; case 2: Console.WriteLine(""M1c""); break; } } M1(1, true); M1(1, false); M1(2, false); M1(3, false); void M2(object o, bool b) { switch (o) { case null: Console.WriteLine(""M2a""); break; case var _ when b: Console.WriteLine(""M2b""); break; case 1: Console.WriteLine(""M2c""); break; } } M2(null, true); M2(1, true); M2(1, false); void M3(bool? b1, bool b2) { switch (b1) { case null: Console.WriteLine(""M3a""); break; case var _ when b2: Console.WriteLine(""M3b""); break; case true: Console.WriteLine(""M3c""); break; case false: Console.WriteLine(""M3d""); break; } } M3(null, true); M3(true, true); M3(true, false); M3(false, false); void M4(object o, bool b) { switch (o) { case var _ when b: Console.WriteLine(""M4a""); break; case int i: Console.WriteLine(""M4b""); break; } } M4(1, true); M4(1, false); void M5(int? i, bool b) { switch (i) { case var _ when b: Console.WriteLine(""M5a""); break; case null: Console.WriteLine(""M5b""); break; case int q: Console.WriteLine(""M5c""); break; } } M5(1, true); M5(null, false); M5(1, false); void M6(object o, bool b) { switch (o) { case var _ when b: Console.WriteLine(""M6a""); break; case object q: Console.WriteLine(""M6b""); break; case null: Console.WriteLine(""M6c""); break; } } M6(null, true); M6(1, false); M6(null, false); void M7(object o, bool b) { switch (o) { case null when b: Console.WriteLine(""M7a""); break; case object q: Console.WriteLine(""M7b""); break; case null: Console.WriteLine(""M7c""); break; } } M7(null, true); M7(1, false); M7(null, false); void M8(object o) { switch (o) { case null when false: throw null; case null: Console.WriteLine(""M8a""); break; } } M8(null); void M9(object o, bool b1, bool b2) { switch (o) { case var _ when b1: Console.WriteLine(""M9a""); break; case var _ when b2: Console.WriteLine(""M9b""); break; case var _: Console.WriteLine(""M9c""); break; } } M9(1, true, false); M9(1, false, true); M9(1, false, false); void M10(bool b) { const string nullString = null; switch (nullString) { case null when b: Console.WriteLine(""M10a""); break; case var _: Console.WriteLine(""M10b""); break; } } M10(true); M10(false); void M11() { const string s = """"; switch (s) { case string _: Console.WriteLine(""M11a""); break; } } M11(); void M12(bool cond) { const string s = """"; switch (s) { case string _ when cond: Console.WriteLine(""M12a""); break; case var _: Console.WriteLine(""M12b""); break; } } M12(true); M12(false); void M13(bool cond) { string s = """"; switch (s) { case string _ when cond: Console.WriteLine(""M13a""); break; case string _: Console.WriteLine(""M13b""); break; } } M13(true); M13(false); void M14() { const string s = """"; switch (s) { case s: Console.WriteLine(""M14a""); break; } } M14(); void M15() { const int i = 3; switch (i) { case 3: case 4: case 5: Console.WriteLine(""M15a""); break; } } M15(); } }"; var expectedOutput = @"M1a M1b M1c M2a M2b M2c M3a M3b M3c M3d M4a M4b M5a M5b M5c M6a M6b M6c M7a M7b M7c M8a M9a M9b M9c M10a M10b M11a M12a M12b M13a M13b M14a M15a "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] [WorkItem(9542, "https://github.com/dotnet/roslyn/issues/9542")] public void DecisionTreeCoverage_BadEquals() { // tests added to complete coverage of the decision tree and pattern-matching implementation var source = @"public class X { static void M1(float o) { switch (o) { case 0f/0f: break; } } } namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } } public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } } public struct Char { } public class String { } } namespace System { public struct Single { private Single m_value; public /*note bad return type*/ void Equals(Single other) { m_value = m_value + 1; } public /*note bad return type*/ void IsNaN(Single other) { } } } "; var compilation = CreateEmptyCompilation(source); compilation.VerifyDiagnostics( ); compilation.GetEmitDiagnostics().Where(d => d.Severity != DiagnosticSeverity.Warning).Verify( // (7,18): error CS0656: Missing compiler required member 'System.Single.IsNaN' // case 0f/0f: break; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "0f/0f").WithArguments("System.Single", "IsNaN").WithLocation(7, 18) ); } [Fact] [WorkItem(9542, "https://github.com/dotnet/roslyn/issues/9542")] public void DecisionTreeCoverage_DuplicateDefault() { // tests added to complete coverage of the decision tree and pattern-matching implementation var source = @"public class X { static void M1(object o) { switch (o) { case int x: default: default: break; } } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (9,13): error CS0152: The switch statement contains multiple cases with the label value 'default' // default: Diagnostic(ErrorCode.ERR_DuplicateCaseLabel, "default:").WithArguments("default").WithLocation(9, 13) ); } [Fact] [WorkItem(9542, "https://github.com/dotnet/roslyn/issues/9542")] public void DecisionTreeCoverage_Negative() { // tests added to complete coverage of the decision tree and pattern-matching implementation var source = @"public class X { static void M1(object o) { switch (o) { case 1: case int _: case 2: // subsumed break; } } static void M2(object o) { switch (o) { case 1: case int _: case int _: // subsumed break; } } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (9,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match. // case 2: // subsumed Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "2").WithLocation(9, 18), // (19,18): error CS8120: The switch case is unreachable. It has already been handled by a previous case or it is impossible to match. // case int _: // subsumed Diagnostic(ErrorCode.ERR_SwitchCaseSubsumed, "int _").WithLocation(19, 18) ); } [Fact] [WorkItem(17089, "https://github.com/dotnet/roslyn/issues/17089")] public void Dynamic_01() { var source = @"using System; public class X { static void M1(dynamic d) { if (d is 1) { Console.Write('r'); } else if (d is int i) { Console.Write('o'); } else if (d is var z) { long l = z; Console.Write('s'); } } static void M2(dynamic d) { switch (d) { case 1: Console.Write('l'); break; case int i: Console.Write('y'); break; case var z: long l = z; Console.Write('n'); break; } } public static void Main(string[] args) { M1(1); M1(2); M1(3L); M2(1); M2(2); M2(3L); } } "; var compilation = CreateCompilation(source, references: new MetadataReference[] { CSharpRef }, options: TestOptions.ReleaseExe); var comp = CompileAndVerify(compilation, expectedOutput: "roslyn"); } [Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")] public void OpenTypeMatch_01() { var source = @"using System; public class Base { } public class Derived : Base { } public class Program { public static void Main(string[] args) { M(new Derived()); M(new Base()); } public static void M<T>(T x) where T: Base { Console.Write(x is Derived b0); switch (x) { case Derived b1: Console.Write(1); break; default: Console.Write(0); break; } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7); compilation.VerifyDiagnostics( // (13,28): error CS8413: An expression of type 'T' cannot be handled by a pattern of type 'Derived' in C# 7.0. Please use language version 7.1 or greater. // Console.Write(x is Derived b0); Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "Derived").WithArguments("T", "Derived", "7.0", "7.1").WithLocation(13, 28), // (16,18): error CS8413: An expression of type 'T' cannot be handled by a pattern of type 'Derived' in C# 7.0. Please use language version 7.1 or greater. // case Derived b1: Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "Derived").WithArguments("T", "Derived", "7.0", "7.1").WithLocation(16, 18) ); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_1); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "True1False0"); } [Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")] public void OpenTypeMatch_02() { var source = @"using System; public class Base { } public class Derived : Base { } public class Program { public static void Main(string[] args) { M<Derived>(new Derived()); M<Derived>(new Base()); } public static void M<T>(Base x) { Console.Write(x is T b0); switch (x) { case T b1: Console.Write(1); break; default: Console.Write(0); break; } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7); compilation.VerifyDiagnostics( // (13,28): error CS8413: An expression of type 'Base' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater. // Console.Write(x is T b0); Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("Base", "T", "7.0", "7.1").WithLocation(13, 28), // (16,18): error CS8413: An expression of type 'Base' cannot be handled by a pattern of type 'T' in C# 7.0. Please use language version 7.1 or greater. // case T b1: Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "T").WithArguments("Base", "T", "7.0", "7.1") ); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_1); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "True1False0"); } [Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")] public void OpenTypeMatch_03() { var source = @"using System; public class Base { } public class Derived<T> : Base { } public class Program { public static void Main(string[] args) { M<Base>(new Derived<Base>()); M<Base>(new Base()); } public static void M<T>(T x) where T: Base { Console.Write(x is Derived<T> b0); switch (x) { case Derived<T> b1: Console.Write(1); break; default: Console.Write(0); break; } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7); compilation.VerifyDiagnostics( // (13,28): error CS8413: An expression of type 'T' cannot be handled by a pattern of type 'Derived<T>' in C# 7.0. Please use language version 7.1 or greater. // Console.Write(x is Derived<T> b0); Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "Derived<T>").WithArguments("T", "Derived<T>", "7.0", "7.1").WithLocation(13, 28), // (16,18): error CS8413: An expression of type 'T' cannot be handled by a pattern of type 'Derived<T>' in C# 7.0. Please use language version 7.1 or greater. // case Derived<T> b1: Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "Derived<T>").WithArguments("T", "Derived<T>", "7.0", "7.1").WithLocation(16, 18) ); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_1); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "True1False0"); } [Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")] public void OpenTypeMatch_04() { var source = @"using System; public class Base { } class Container<T> { public class Derived : Base { } } public class Program { public static void Main(string[] args) { M<Base>(new Container<Base>.Derived()); M<Base>(new Base()); } public static void M<T>(T x) where T: Base { Console.Write(x is Container<T>.Derived b0); switch (x) { case Container<T>.Derived b1: Console.Write(1); break; default: Console.Write(0); break; } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7); compilation.VerifyDiagnostics( // (16,28): error CS8413: An expression of type 'T' cannot be handled by a pattern of type 'Container<T>.Derived' in C# 7.0. Please use language version 7.1 or greater. // Console.Write(x is Container<T>.Derived b0); Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "Container<T>.Derived").WithArguments("T", "Container<T>.Derived", "7.0", "7.1").WithLocation(16, 28), // (19,18): error CS8413: An expression of type 'T' cannot be handled by a pattern of type 'Container<T>.Derived' in C# 7.0. Please use language version 7.1 or greater. // case Container<T>.Derived b1: Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "Container<T>.Derived").WithArguments("T", "Container<T>.Derived", "7.0", "7.1").WithLocation(19, 18) ); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_1); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "True1False0"); } [Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")] public void OpenTypeMatch_05() { var source = @"using System; public class Base { } class Container<T> { public class Derived : Base { } } public class Program { public static void Main(string[] args) { M<Base>(new Container<Base>.Derived[1]); M<Base>(new Base[1]); } public static void M<T>(T[] x) where T: Base { Console.Write(x is Container<T>.Derived[] b0); switch (x) { case Container<T>.Derived[] b1: Console.Write(1); break; default: Console.Write(0); break; } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7); compilation.VerifyDiagnostics( // (16,28): error CS8413: An expression of type 'T[]' cannot be handled by a pattern of type 'Container<T>.Derived[]' in C# 7.0. Please use language version 7.1 or greater. // Console.Write(x is Container<T>.Derived[] b0); Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "Container<T>.Derived[]").WithArguments("T[]", "Container<T>.Derived[]", "7.0", "7.1").WithLocation(16, 28), // (19,18): error CS8413: An expression of type 'T[]' cannot be handled by a pattern of type 'Container<T>.Derived[]' in C# 7.0. Please use language version 7.1 or greater. // case Container<T>.Derived[] b1: Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "Container<T>.Derived[]").WithArguments("T[]", "Container<T>.Derived[]", "7.0", "7.1").WithLocation(19, 18) ); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular7_1); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: "True1False0"); } [Fact, WorkItem(19151, "https://github.com/dotnet/roslyn/issues/19151")] public void RefutablePatterns() { var source = @"public class Program { public static void Main(string[] args) { if (null as string is string) { } if (null as string is string s1) { } const string s = null; if (s is string) { } if (s is string s2) { } if (""goo"" is string s3) { } } void M1(int? i) { if (i is long) { } if (i is long l) { } switch (b) { case long m: break; } } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (8,13): warning CS0184: The given expression is never of the provided ('string') type // if (s is string) { } Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "s is string").WithArguments("string").WithLocation(8, 13), // (9,13): warning CS8416: The given expression never matches the provided pattern. // if (s is string s2) { } Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "s is string s2").WithLocation(9, 13), // (14,13): warning CS0184: The given expression is never of the provided ('long') type // if (i is long) { } Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "i is long").WithArguments("long").WithLocation(14, 13), // (15,18): error CS8121: An expression of type 'int?' cannot be handled by a pattern of type 'long'. // if (i is long l) { } Diagnostic(ErrorCode.ERR_PatternWrongType, "long").WithArguments("int?", "long").WithLocation(15, 18), // (16,17): error CS0103: The name 'b' does not exist in the current context // switch (b) { case long m: break; } Diagnostic(ErrorCode.ERR_NameNotInContext, "b").WithArguments("b").WithLocation(16, 17) ); } [Fact, WorkItem(19038, "https://github.com/dotnet/roslyn/issues/19038")] public void GenericDynamicIsObject() { var program = @" using System; public class Program { static void Main(string[] args) { M<dynamic>(new object()); M<dynamic>(null); M<dynamic>(""xyzzy""); } static void M<T>(object x) { switch (x) { case T t: Console.Write(""T""); break; case null: Console.Write(""n""); break; } } } "; var compilation = CreateCompilation(program, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"TnT"); } [Fact, WorkItem(19038, "https://github.com/dotnet/roslyn/issues/19038")] public void MatchNullableTypeParameter() { var program = @" using System; public class Program { static void Main(string[] args) { M<int>(1); M<int>(null); M<float>(3.14F); } static void M<T>(T? x) where T : struct { switch (x) { case T t: Console.Write(""T""); break; case null: Console.Write(""n""); break; } } } "; var compilation = CreateCompilation(program, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"TnT"); } [Fact, WorkItem(16195, "https://github.com/dotnet/roslyn/issues/16195")] public void MatchRecursiveGenerics() { var program = @"using System; class Packet { } class Packet<U> : Packet { } public class C { static void Main() { Console.Write(M<Packet>(null)); Console.Write(M<Packet>(new Packet<Packet>())); Console.Write(M<Packet>(new Packet<int>())); Console.Write(M<Packet<int>>(new Packet<int>())); } static bool M<T>(T p) where T : Packet => p is Packet<T> p1; }"; CreateCompilation(program, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7).VerifyDiagnostics( // (12,52): error CS8314: An expression of type 'T' cannot be handled by a pattern of type 'Packet<T>' in C# 7.0. Please use language version 7.1 or greater. // static bool M<T>(T p) where T : Packet => p is Packet<T> p1; Diagnostic(ErrorCode.ERR_PatternWrongGenericTypeInVersion, "Packet<T>").WithArguments("T", "Packet<T>", "7.0", "7.1").WithLocation(12, 52) ); var compilation = CreateCompilation(program, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_1); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"FalseTrueFalseFalse"); } [Fact, WorkItem(19038, "https://github.com/dotnet/roslyn/issues/19038")] public void MatchRestrictedTypes_Fail() { var program = @"using System; unsafe public class C { static bool M(TypedReference x, int* p, ref int z) { var n1 = x is TypedReference x0; // ok var p1 = p is int* p0; // syntax error 1 var r1 = z is ref int z0; // syntax error 2 var b1 = x is object o1; // not allowed 1 var b2 = p is object o2; // not allowed 2 var b3 = z is object o3; // ok return b1 && b2 && b3; } }"; var compilation = CreateCompilation(program, options: TestOptions.DebugDll.WithAllowUnsafe(true)); compilation.VerifyDiagnostics( // (6,23): error CS1525: Invalid expression term 'int' // var p1 = p is int* p0; // syntax error 1 Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(6, 23), // (7,23): error CS1525: Invalid expression term 'ref' // var r1 = z is ref int z0; // syntax error 2 Diagnostic(ErrorCode.ERR_InvalidExprTerm, "ref int").WithArguments("ref").WithLocation(7, 23), // (7,27): error CS1525: Invalid expression term 'int' // var r1 = z is ref int z0; // syntax error 2 Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(7, 27), // (7,31): error CS1002: ; expected // var r1 = z is ref int z0; // syntax error 2 Diagnostic(ErrorCode.ERR_SemicolonExpected, "z0").WithLocation(7, 31), // (6,28): error CS0103: The name 'p0' does not exist in the current context // var p1 = p is int* p0; // syntax error 1 Diagnostic(ErrorCode.ERR_NameNotInContext, "p0").WithArguments("p0").WithLocation(6, 28), // (7,23): error CS1073: Unexpected token 'ref' // var r1 = z is ref int z0; // syntax error 2 Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(7, 23), // (7,31): error CS0103: The name 'z0' does not exist in the current context // var r1 = z is ref int z0; // syntax error 2 Diagnostic(ErrorCode.ERR_NameNotInContext, "z0").WithArguments("z0").WithLocation(7, 31), // (7,31): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // var r1 = z is ref int z0; // syntax error 2 Diagnostic(ErrorCode.ERR_IllegalStatement, "z0").WithLocation(7, 31), // (9,23): error CS8121: An expression of type 'TypedReference' cannot be handled by a pattern of type 'object'. // var b1 = x is object o1; // not allowed 1 Diagnostic(ErrorCode.ERR_PatternWrongType, "object").WithArguments("System.TypedReference", "object").WithLocation(9, 23), // (10,23): error CS8521: Pattern-matching is not permitted for pointer types. // var b2 = p is object o2; // not allowed 2 Diagnostic(ErrorCode.ERR_PointerTypeInPatternMatching, "object").WithLocation(10, 23) ); } [Fact, WorkItem(19038, "https://github.com/dotnet/roslyn/issues/19038")] public void MatchRestrictedTypes_Success() { var program = @"using System; using System.Reflection; unsafe public class C { public int Value; static void Main() { C a = new C { Value = 12 }; FieldInfo info = typeof(C).GetField(""Value""); TypedReference reference = __makeref(a); if (!(reference is TypedReference reference0)) throw new Exception(""TypedReference""); info.SetValueDirect(reference0, 34); if (a.Value != 34) throw new Exception(""SetValueDirect""); int z = 56; if (CopyRefInt(ref z) != 56) throw new Exception(""ref z""); Console.WriteLine(""ok""); } static int CopyRefInt(ref int z) { if (!(z is int z0)) throw new Exception(""CopyRefInt""); return z0; } }"; var compilation = CreateCompilation(program, options: TestOptions.DebugExe.WithAllowUnsafe(true)); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: "ok"); } [Fact] [WorkItem(406203, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=406203")] [WorkItem(406205, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=406205")] public void DoubleEvaluation() { var source = @"using System; public class X { public static void Main(string[] args) { { int? a = 0; if (a++ is int b) { Console.WriteLine(b); } Console.WriteLine(a); } { int? a = 0; if (++a is int b) { Console.WriteLine(b); } Console.WriteLine(a); } { if (Func() is int b) { Console.WriteLine(b); } } } public static int? Func() { Console.WriteLine(""Func called""); return 2; } } "; var expectedOutput = @"0 1 1 1 Func called 2"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: expectedOutput); compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void TestVoidInIsOrAs_01() { // though silly, it is not forbidden to test a void value's type var source = @"using System; class Program { static void Main() { if (Console.Write(""Hello"") is object) {} } } "; var expectedOutput = @"Hello"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (6,13): warning CS0184: The given expression is never of the provided ('object') type // if (Console.Write("Hello") is object) {} Diagnostic(ErrorCode.WRN_IsAlwaysFalse, @"Console.Write(""Hello"") is object").WithArguments("object").WithLocation(6, 13) ); CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact] public void TestVoidInIsOrAs_02() { var source = @"using System; class Program { static void Main() { var o = Console.WriteLine(""world!"") as object; if (o != null) throw null; } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (6,17): error CS0039: Cannot convert type 'void' to 'object' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion // var o = Console.WriteLine("world!") as object; Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, @"Console.WriteLine(""world!"") as object").WithArguments("void", "object").WithLocation(6, 17) ); } [Fact] public void TestVoidInIsOrAs_03() { var source = @"using System; class Program { static void Main() { M<object>(); } static void M<T>() where T : class { var o = Console.WriteLine(""Hello"") as T; if (o != null) throw null; } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (10,17): error CS0039: Cannot convert type 'void' to 'T' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion // var o = Console.WriteLine("Hello") as T; Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, @"Console.WriteLine(""Hello"") as T").WithArguments("void", "T").WithLocation(10, 17) ); } [Fact] public void TestVoidInIsOrAs_04() { var source = @"using System; class Program { static void Main() { if (Console.WriteLine(""Hello"") is var x) { } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (6,13): error CS8117: Invalid operand for pattern match; value required, but found 'void'. // if (Console.WriteLine("Hello") is var x) { } Diagnostic(ErrorCode.ERR_BadPatternExpression, @"Console.WriteLine(""Hello"")").WithArguments("void").WithLocation(6, 13) ); } [Fact] public void TestVoidInIsOrAs_05() { var source = @"using System; class Program { static void Main() { if (Console.WriteLine(""Hello"") is var _) {} } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (6,13): error CS8117: Invalid operand for pattern match; value required, but found 'void'. // if (Console.WriteLine("Hello") is var _) {} Diagnostic(ErrorCode.ERR_BadPatternExpression, @"Console.WriteLine(""Hello"")").WithArguments("void").WithLocation(6, 13) ); } [Fact] public void TestVoidInSwitch() { var source = @"using System; class Program { static void Main() { switch (Console.WriteLine(""Hello"")) { default: break; } } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (6,17): error CS8119: The switch expression must be a value; found 'void'. // switch (Console.WriteLine("Hello")) Diagnostic(ErrorCode.ERR_SwitchExpressionValueExpected, @"Console.WriteLine(""Hello"")").WithArguments("void").WithLocation(6, 17) ); } [Fact, WorkItem(20103, "https://github.com/dotnet/roslyn/issues/20103")] public void TestNullInIsPattern() { var source = @"using System; class Program { static void Main() { const string s = null; if (s is string) {} else { Console.Write(""Hello ""); } if (s is string t) {} else { Console.WriteLine(""World""); } } } "; var expectedOutput = @"Hello World"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (7,13): warning CS0184: The given expression is never of the provided ('string') type // if (s is string) {} else { Console.Write("Hello "); } Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "s is string").WithArguments("string").WithLocation(7, 13), // (8,13): warning CS8416: The given expression never matches the provided pattern. // if (s is string t) {} else { Console.WriteLine("World"); } Diagnostic(ErrorCode.WRN_GivenExpressionNeverMatchesPattern, "s is string t").WithLocation(8, 13) ); CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact, WorkItem(22619, "https://github.com/dotnet/roslyn/issues/22619")] public void MissingSideEffect() { var source = @"using System; internal class Program { private static void Main() { try { var test = new Program(); var result = test.IsVarMethod(); Console.WriteLine($""Result = {result}""); Console.Read(); } catch (Exception) { Console.WriteLine(""Exception""); } } private int IsVarMethod() => ThrowingMethod() is var _ ? 1 : 0; private bool ThrowingMethod() => throw new Exception(""Oh""); } "; var expectedOutput = @"Exception"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void TestArrayOfPointer() { var source = @"using System; class Program { unsafe static void Main() { object o = new byte*[10]; Console.WriteLine(o is byte*[]); // True Console.WriteLine(o is byte*[] _); // True Console.WriteLine(o is byte*[] x1); // True Console.WriteLine(o is byte**[]); // False Console.WriteLine(o is byte**[] _); // False Console.WriteLine(o is byte**[] x2); // False o = new byte**[10]; Console.WriteLine(o is byte**[]); // True Console.WriteLine(o is byte**[] _); // True Console.WriteLine(o is byte**[] x3); // True Console.WriteLine(o is byte*[]); // False Console.WriteLine(o is byte*[] _); // False Console.WriteLine(o is byte*[] x4); // False } } "; var expectedOutput = @"True True True False False False True True True False False False"; var compilation = CreateCompilation(source, options: TestOptions.UnsafeReleaseExe); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: expectedOutput, verify: Verification.Fails); } [Fact] public void DefaultPattern() { var source = @"class Program { public static void Main() { int i = 12; if (i is default) {} // error 1 if (i is (default)) {} // error 2 if (i is (((default)))) {} // error 3 switch (i) { case default: break; } // error 4 switch (i) { case (default): break; } // error 5 switch (i) { case default when true: break; } // error 6 switch (i) { case (default) when true: break; } // error 7 } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (6,18): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (i is default) {} // error 1 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(6, 18), // (7,19): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (i is (default)) {} // error 2 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(7, 19), // (8,21): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (i is (((default)))) {} // error 3 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(8, 21), // (9,27): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // switch (i) { case default: break; } // error 4 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(9, 27), // (10,28): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // switch (i) { case (default): break; } // error 5 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(10, 28), // (11,27): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // switch (i) { case default when true: break; } // error 6 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(11, 27), // (12,28): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // switch (i) { case (default) when true: break; } // error 7 Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(12, 28) ); var tree = compilation.SyntaxTrees.Single(); var caseDefault = tree.GetRoot().DescendantNodes().OfType<CasePatternSwitchLabelSyntax>().First(); var model = compilation.GetSemanticModel(tree, ignoreAccessibility: false); Assert.Equal("System.Int32", model.GetTypeInfo(caseDefault.Pattern).Type.ToTestDisplayString()); Assert.Equal("System.Int32", model.GetTypeInfo(caseDefault.Pattern).ConvertedType.ToTestDisplayString()); Assert.False(model.GetConstantValue(caseDefault.Pattern).HasValue); } [Fact] public void EventInitializers_01() { var source = @" public class X { public static void Main() { System.Console.WriteLine(Test1()); } static event System.Func<bool> Test1 = GetDelegate(1 is int x1 && Dummy(x1)); static System.Func<bool> GetDelegate(bool value) => () => value; static bool Dummy(int x) { System.Console.WriteLine(x); return true; } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"1 True"); CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics( // (9,65): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater. // static event System.Func<bool> Test1 = GetDelegate(1 is int x1 && Dummy(x1)); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "x1").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(9, 65) ); } [Fact] public void ExhaustiveBoolSwitch00() { // Note that the switches in this code are exhaustive. The idea of a switch // being exhaustive is new with the addition of pattern-matching; this code // used to give errors that are no longer applicable due to the spec change. var source = @" using System; public class C { public static void Main() { M(true); M(false); Console.WriteLine(M2(true)); Console.WriteLine(M2(false)); } public static void M(bool e) { bool b; switch (e) { case true: b = true; break; case false: b = false; break; } Console.WriteLine(b); // no more error CS0165: Use of unassigned local variable 'b' } public static bool M2(bool e) // no more error CS0161: not all code paths return a value { switch (e) { case true: return true; case false: return false; } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"True False True False"); } [Fact, WorkItem(24865, "https://github.com/dotnet/roslyn/issues/24865")] public void ExhaustiveBoolSwitch01() { var source = @" using System; public class C { public static void Main() { M(true); M(false); Console.WriteLine(M2(true)); Console.WriteLine(M2(false)); } public static void M(bool e) { bool b; switch (e) { case true when true: b = true; break; case false: b = false; break; } Console.WriteLine(b); } public static bool M2(bool e) { switch (e) { case true when true: return true; case false: return false; } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( ); var comp = CompileAndVerify(compilation, expectedOutput: @"True False True False"); } [Fact] [WorkItem(27218, "https://github.com/dotnet/roslyn/issues/27218")] public void IsPatternMatchingDoesNotCopyEscapeScopes_01() { CreateCompilationWithMscorlibAndSpan(@" using System; public class C { public ref int M() { Span<int> outer = stackalloc int[100]; if (outer is Span<int> inner) { return ref inner[5]; } throw null; } }").VerifyDiagnostics( // (10,24): error CS8352: Cannot use local 'inner' in this context because it may expose referenced variables outside of their declaration scope // return ref inner[5]; Diagnostic(ErrorCode.ERR_EscapeLocal, "inner").WithArguments("inner").WithLocation(10, 24)); } [Fact] [WorkItem(27218, "https://github.com/dotnet/roslyn/issues/27218")] public void IsPatternMatchingDoesNotCopyEscapeScopes_03() { CreateCompilationWithMscorlibAndSpan(parseOptions: TestOptions.RegularWithPatternCombinators, text: @" using System; public class C { public ref int M() { Span<int> outer = stackalloc int[100]; if (outer is ({} and var x) and Span<int> inner) { return ref inner[5]; } throw null; } }").VerifyDiagnostics( // (8,13): warning CS8794: An expression of type 'Span<int>' always matches the provided pattern. // if (outer is ({} and var x) and Span<int> inner) Diagnostic(ErrorCode.WRN_IsPatternAlways, "outer is ({} and var x) and Span<int> inner").WithArguments("System.Span<int>").WithLocation(8, 13), // (10,24): error CS8352: Cannot use local 'inner' in this context because it may expose referenced variables outside of their declaration scope // return ref inner[5]; Diagnostic(ErrorCode.ERR_EscapeLocal, "inner").WithArguments("inner").WithLocation(10, 24) ); } [Fact] [WorkItem(27218, "https://github.com/dotnet/roslyn/issues/27218")] public void CasePatternMatchingDoesNotCopyEscapeScopes_01() { CreateCompilationWithMscorlibAndSpan(@" using System; public class C { public ref int M() { Span<int> outer = stackalloc int[100]; switch (outer) { case Span<int> inner: { return ref inner[5]; } } throw null; } }").VerifyDiagnostics( // (12,28): error CS8352: Cannot use local 'inner' in this context because it may expose referenced variables outside of their declaration scope // return ref inner[5]; Diagnostic(ErrorCode.ERR_EscapeLocal, "inner").WithArguments("inner").WithLocation(12, 28)); } [Fact] [WorkItem(27218, "https://github.com/dotnet/roslyn/issues/27218")] public void CasePatternMatchingDoesNotCopyEscapeScopes_03() { CreateCompilationWithMscorlibAndSpan(parseOptions: TestOptions.RegularWithPatternCombinators, text: @" using System; public class C { public ref int M() { Span<int> outer = stackalloc int[100]; switch (outer) { case {} and Span<int> inner: { return ref inner[5]; } } throw null; } }").VerifyDiagnostics( // (12,28): error CS8352: Cannot use local 'inner' in this context because it may expose referenced variables outside of their declaration scope // return ref inner[5]; Diagnostic(ErrorCode.ERR_EscapeLocal, "inner").WithArguments("inner").WithLocation(12, 28)); } [Fact] [WorkItem(28633, "https://github.com/dotnet/roslyn/issues/28633")] public void CasePatternMatchingDoesNotCopyEscapeScopes_02() { CreateCompilationWithMscorlibAndSpan(parseOptions: TestOptions.RegularWithRecursivePatterns, text: @" using System; public ref struct R { public R Prop => this; public void Deconstruct(out R X, out R Y) => X = Y = this; public static implicit operator R(Span<int> span) => new R(); } public class C { public R M1() { R outer = stackalloc int[100]; switch (outer) { case { Prop: var x }: return x; // error 1 } } public R M2() { R outer = stackalloc int[100]; switch (outer) { case { Prop: R x }: return x; // error 2 } } public R M3() { R outer = stackalloc int[100]; switch (outer) { case (var x, var y): return x; // error 3 } } public R M4() { R outer = stackalloc int[100]; switch (outer) { case (R x, R y): return x; // error 4 } } public R M5() { R outer = stackalloc int[100]; switch (outer) { case var (x, y): return x; // error 5 } } public R M6() { R outer = stackalloc int[100]; switch (outer) { case { } x: return x; // error 6 } } public R M7() { R outer = stackalloc int[100]; switch (outer) { case (_, _) x: return x; // error 7 } } } ").VerifyDiagnostics( // (16,42): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // case { Prop: var x }: return x; // error 1 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(16, 42), // (24,40): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // case { Prop: R x }: return x; // error 2 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(24, 40), // (32,41): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // case (var x, var y): return x; // error 3 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(32, 41), // (40,37): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // case (R x, R y): return x; // error 4 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(40, 37), // (48,37): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // case var (x, y): return x; // error 5 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(48, 37), // (56,32): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // case { } x: return x; // error 6 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(56, 32), // (64,35): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // case (_, _) x: return x; // error 7 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(64, 35) ); } [Fact] [WorkItem(28633, "https://github.com/dotnet/roslyn/issues/28633")] public void CasePatternMatchingDoesNotCopyEscapeScopes_04() { CreateCompilationWithMscorlibAndSpan(parseOptions: TestOptions.RegularWithPatternCombinators, text: @" using System; public ref struct R { public R Prop => this; public void Deconstruct(out R X, out R Y) => X = Y = this; public static implicit operator R(Span<int> span) => new R(); } public class C { public R M1() { R outer = stackalloc int[100]; switch (outer) { case var _ and {} and { Prop: var _ and {} and var x }: return x; // error 1 } } public R M2() { R outer = stackalloc int[100]; switch (outer) { case var _ and {} and { Prop: var _ and {} and R x }: return x; // error 2 } } public R M3() { R outer = stackalloc int[100]; switch (outer) { case var _ and {} and (var _ and {} and var x, var _ and {} and var y): return x; // error 3 } } public R M4() { R outer = stackalloc int[100]; switch (outer) { case var _ and {} and (var _ and {} and R x, var _ and {} and R y): return x; // error 4 } } public R M5() { R outer = stackalloc int[100]; switch (outer) { case var _ and {} and var (x, y): return x; // error 5 } } public R M6() { R outer = stackalloc int[100]; switch (outer) { case var _ and {} and { } x: return x; // error 6 } } public R M7() { R outer = stackalloc int[100]; switch (outer) { case var _ and {} and (var _ and {} and _, var _ and {} and _) x: return x; // error 7 } } } ").VerifyDiagnostics( // (16,76): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // case var _ and {} and { Prop: var _ and {} and var x }: return x; // error 1 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(16, 76), // (24,74): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // case var _ and {} and { Prop: var _ and {} and R x }: return x; // error 2 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(24, 74), // (32,92): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // case var _ and {} and (var _ and {} and var x, var _ and {} and var y): return x; // error 3 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(32, 92), // (40,88): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // case var _ and {} and (var _ and {} and R x, var _ and {} and R y): return x; // error 4 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(40, 88), // (48,54): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // case var _ and {} and var (x, y): return x; // error 5 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(48, 54), // (56,49): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // case var _ and {} and { } x: return x; // error 6 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(56, 49), // (64,86): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // case var _ and {} and (var _ and {} and _, var _ and {} and _) x: return x; // error 7 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(64, 86) ); } [Fact] [WorkItem(28633, "https://github.com/dotnet/roslyn/issues/28633")] public void IsPatternMatchingDoesNotCopyEscapeScopes_02() { CreateCompilationWithMscorlibAndSpan(parseOptions: TestOptions.RegularWithRecursivePatterns, text: @" using System; public ref struct R { public R Prop => this; public void Deconstruct(out R X, out R Y) => X = Y = this; public static implicit operator R(Span<int> span) => new R(); } public class C { public R M1() { R outer = stackalloc int[100]; if (outer is { Prop: var x }) return x; // error 1 throw null; } public R M2() { R outer = stackalloc int[100]; if (outer is { Prop: R x }) return x; // error 2 throw null; } public R M3() { R outer = stackalloc int[100]; if (outer is (var x, var y)) return x; // error 3 throw null; } public R M4() { R outer = stackalloc int[100]; if (outer is (R x, R y)) return x; // error 4 throw null; } public R M5() { R outer = stackalloc int[100]; if (outer is var (x, y)) return x; // error 5 throw null; } public R M6() { R outer = stackalloc int[100]; if (outer is { } x) return x; // error 6 throw null; } public R M7() { R outer = stackalloc int[100]; if (outer is (_, _) x) return x; // error 7 throw null; } } ").VerifyDiagnostics( // (14,46): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // if (outer is { Prop: var x }) return x; // error 1 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(14, 46), // (20,44): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // if (outer is { Prop: R x }) return x; // error 2 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(20, 44), // (26,45): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // if (outer is (var x, var y)) return x; // error 3 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(26, 45), // (32,41): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // if (outer is (R x, R y)) return x; // error 4 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(32, 41), // (38,41): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // if (outer is var (x, y)) return x; // error 5 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(38, 41), // (44,36): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // if (outer is { } x) return x; // error 6 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(44, 36), // (50,39): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // if (outer is (_, _) x) return x; // error 7 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(50, 39) ); } [Fact] [WorkItem(28633, "https://github.com/dotnet/roslyn/issues/28633")] public void IsPatternMatchingDoesNotCopyEscapeScopes_04() { CreateCompilationWithMscorlibAndSpan(parseOptions: TestOptions.RegularWithPatternCombinators, text: @" using System; public ref struct R { public R Prop => this; public void Deconstruct(out R X, out R Y) => X = Y = this; public static implicit operator R(Span<int> span) => new R(); } public class C { public R M1() { R outer = stackalloc int[100]; if (outer is var _ and {} and { Prop: var _ and {} and var x }) return x; // error 1 throw null; } public R M2() { R outer = stackalloc int[100]; if (outer is var _ and {} and { Prop: var _ and {} and R x }) return x; // error 2 throw null; } public R M3() { R outer = stackalloc int[100]; if (outer is var _ and {} and (var _ and {} and var x, var _ and {} and var y)) return x; // error 3 throw null; } public R M4() { R outer = stackalloc int[100]; if (outer is var _ and {} and (var _ and {} and R x, var _ and {} and R y)) return x; // error 4 throw null; } public R M5() { R outer = stackalloc int[100]; if (outer is var _ and {} and var (x, y)) return x; // error 5 throw null; } public R M6() { R outer = stackalloc int[100]; if (outer is var _ and {} and { } x) return x; // error 6 throw null; } public R M7() { R outer = stackalloc int[100]; if (outer is var _ and {} and (_, _) x) return x; // error 7 throw null; } } ").VerifyDiagnostics( // if (outer is var _ and {} and { Prop: var _ and {} and var x }) return x; // error 1 Diagnostic(ErrorCode.WRN_IsPatternAlways, "outer is var _ and {} and { Prop: var _ and {} and var x }").WithArguments("R").WithLocation(14, 13), // (14,80): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // if (outer is var _ and {} and { Prop: var _ and {} and var x }) return x; // error 1 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(14, 80), // (20,13): warning CS8794: An expression of type 'R' always matches the provided pattern. // if (outer is var _ and {} and { Prop: var _ and {} and R x }) return x; // error 2 Diagnostic(ErrorCode.WRN_IsPatternAlways, "outer is var _ and {} and { Prop: var _ and {} and R x }").WithArguments("R").WithLocation(20, 13), // (20,78): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // if (outer is var _ and {} and { Prop: var _ and {} and R x }) return x; // error 2 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(20, 78), // (26,13): warning CS8794: An expression of type 'R' always matches the provided pattern. // if (outer is var _ and {} and (var _ and {} and var x, var _ and {} and var y)) return x; // error 3 Diagnostic(ErrorCode.WRN_IsPatternAlways, "outer is var _ and {} and (var _ and {} and var x, var _ and {} and var y)").WithArguments("R").WithLocation(26, 13), // (26,96): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // if (outer is var _ and {} and (var _ and {} and var x, var _ and {} and var y)) return x; // error 3 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(26, 96), // (32,13): warning CS8794: An expression of type 'R' always matches the provided pattern. // if (outer is var _ and {} and (var _ and {} and R x, var _ and {} and R y)) return x; // error 4 Diagnostic(ErrorCode.WRN_IsPatternAlways, "outer is var _ and {} and (var _ and {} and R x, var _ and {} and R y)").WithArguments("R").WithLocation(32, 13), // (32,92): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // if (outer is var _ and {} and (var _ and {} and R x, var _ and {} and R y)) return x; // error 4 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(32, 92), // (38,13): warning CS8794: An expression of type 'R' always matches the provided pattern. // if (outer is var _ and {} and var (x, y)) return x; // error 5 Diagnostic(ErrorCode.WRN_IsPatternAlways, "outer is var _ and {} and var (x, y)").WithArguments("R").WithLocation(38, 13), // (38,58): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // if (outer is var _ and {} and var (x, y)) return x; // error 5 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(38, 58), // (44,13): warning CS8794: An expression of type 'R' always matches the provided pattern. // if (outer is var _ and {} and { } x) return x; // error 6 Diagnostic(ErrorCode.WRN_IsPatternAlways, "outer is var _ and {} and { } x").WithArguments("R").WithLocation(44, 13), // (44,53): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // if (outer is var _ and {} and { } x) return x; // error 6 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(44, 53), // (50,13): warning CS8794: An expression of type 'R' always matches the provided pattern. // if (outer is var _ and {} and (_, _) x) return x; // error 7 Diagnostic(ErrorCode.WRN_IsPatternAlways, "outer is var _ and {} and (_, _) x").WithArguments("R").WithLocation(50, 13), // (50,56): error CS8352: Cannot use local 'x' in this context because it may expose referenced variables outside of their declaration scope // if (outer is var _ and {} and (_, _) x) return x; // error 7 Diagnostic(ErrorCode.ERR_EscapeLocal, "x").WithArguments("x").WithLocation(50, 56) ); } [Fact] [WorkItem(28633, "https://github.com/dotnet/roslyn/issues/28633")] public void EscapeScopeInSubpatternOfNonRefType() { CreateCompilationWithMscorlibAndSpan(parseOptions: TestOptions.RegularWithRecursivePatterns, text: @" using System; public ref struct R { public R RProp => this; public S SProp => new S(); public void Deconstruct(out S X, out S Y) => X = Y = new S(); public static implicit operator R(Span<int> span) => new R(); } public struct S { public R RProp => new R(); } public class C { public R M1() { R outer = stackalloc int[100]; if (outer is { SProp: { RProp: var x }}) return x; // OK throw null; } public R M2() { R outer = stackalloc int[100]; switch (outer) { case { SProp: { RProp: var x }}: return x; // OK } } public R M3() { R outer = stackalloc int[100]; if (outer is ({ RProp: var x }, _)) return x; // OK throw null; } public R M4() { R outer = stackalloc int[100]; switch (outer) { case ({ RProp: var x }, _): return x; // OK } } } ").VerifyDiagnostics( ); } [Fact] [WorkItem(39960, "https://github.com/dotnet/roslyn/issues/39960")] public void MissingExceptionType() { var source = @" class C { void M(bool b, dynamic d) { _ = b ? throw new System.NullReferenceException() : throw null; L(); throw null; void L() => throw d; } } "; var comp = CreateCompilation(source); comp.MakeTypeMissing(WellKnownType.System_Exception); comp.VerifyDiagnostics( // (7,21): error CS0518: Predefined type 'System.Exception' is not defined or imported // ? throw new System.NullReferenceException() Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "new System.NullReferenceException()").WithArguments("System.Exception").WithLocation(7, 21), // (8,21): error CS0518: Predefined type 'System.Exception' is not defined or imported // : throw null; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "null").WithArguments("System.Exception").WithLocation(8, 21), // (10,15): error CS0518: Predefined type 'System.Exception' is not defined or imported // throw null; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "null").WithArguments("System.Exception").WithLocation(10, 15), // (11,27): error CS0518: Predefined type 'System.Exception' is not defined or imported // void L() => throw d; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "d").WithArguments("System.Exception").WithLocation(11, 27) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.MakeTypeMissing(WellKnownType.System_Exception); comp.VerifyDiagnostics( // (7,21): error CS0155: The type caught or thrown must be derived from System.Exception // ? throw new System.NullReferenceException() Diagnostic(ErrorCode.ERR_BadExceptionType, "new System.NullReferenceException()").WithLocation(7, 21), // (11,27): error CS0155: The type caught or thrown must be derived from System.Exception // void L() => throw d; Diagnostic(ErrorCode.ERR_BadExceptionType, "d").WithLocation(11, 27) ); } [Fact] public void MissingExceptionType_In7() { var source = @" class C { static void Main() { try { Test(); } catch { System.Console.WriteLine(""in catch""); } } static void Test() { throw null; } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7); comp.MakeTypeMissing(WellKnownType.System_Exception); comp.VerifyDiagnostics( ); CompileAndVerify(comp, expectedOutput: "in catch"); } [Fact, WorkItem(50301, "https://github.com/dotnet/roslyn/issues/50301")] public void SymbolsForSwitchExpressionLocals() { var source = @" class C { static string M(object o) { return o switch { int i => $""Number: {i}"", _ => ""Don't know"" }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); comp.VerifyPdb("C.M", @" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""M"" parameterNames=""o""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""9"" endLine=""10"" endColumn=""11"" document=""1"" /> <entry offset=""0xf"" startLine=""8"" startColumn=""22"" endLine=""8"" endColumn=""36"" document=""1"" /> <entry offset=""0x22"" startLine=""9"" startColumn=""18"" endLine=""9"" endColumn=""30"" document=""1"" /> <entry offset=""0x28"" hidden=""true"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2a""> <scope startOffset=""0xf"" endOffset=""0x22""> <local name=""i"" il_index=""0"" il_start=""0xf"" il_end=""0x22"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols> "); } } }
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Interactive/Host/PublicAPI.Unshipped.txt
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/InvertIf/InvertIfTests.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.InvertIf; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.InvertIf { public partial class InvertIfTests : AbstractCSharpCodeActionTest { private async Task TestFixOneAsync( string initial, string expected) { await TestInRegularAndScriptAsync(CreateTreeText(initial), CreateTreeText(expected)); } protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpInvertIfCodeRefactoringProvider(); private static string CreateTreeText(string initial) { return @"class A { bool a = true; bool b = true; bool c = true; bool d = true; void Goo() { " + initial + @" } }"; } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Identifier() { await TestFixOneAsync( @"[||]if (a) { a(); } else { b(); }", @"if (!a) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_IdentifierWithTrivia() { await TestFixOneAsync( @"[||]if /*0*/(/*1*/a/*2*/)/*3*/ { a(); } else { b(); }", @"if /*0*/(/*1*/!a/*2*/)/*3*/ { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_NotIdentifier() { await TestFixOneAsync( @"[||]if (!a) { a(); } else { b(); }", @"if (a) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_NotIdentifierWithTrivia() { await TestFixOneAsync( @"[||]if /*0*/(/*1*/!/*1b*/a/*2*/)/*3*/ { a(); } else { b(); }", @"if /*0*/(/*1*/a/*2*/)/*3*/ { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_EqualsEquals() { await TestFixOneAsync( @"[||]if (a == b) { a(); } else { b(); }", @"if (a != b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_NotEquals() { await TestFixOneAsync( @"[||]if (a != b) { a(); } else { b(); }", @"if (a == b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_GreaterThan() { await TestFixOneAsync( @"[||]if (a > b) { a(); } else { b(); }", @"if (a <= b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_GreaterThanEquals() { await TestFixOneAsync( @"[||]if (a >= b) { a(); } else { b(); }", @"if (a < b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_LessThan() { await TestFixOneAsync( @"[||]if (a < b) { a(); } else { b(); }", @"if (a >= b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_LessThanEquals() { await TestFixOneAsync( @"[||]if (a <= b) { a(); } else { b(); }", @"if (a > b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_DoubleParentheses() { await TestFixOneAsync( @"[||]if ((a)) { a(); } else { b(); }", @"if (!a) { b(); } else { a(); }"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/26427"), Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_DoubleParenthesesWithInnerTrivia() { await TestFixOneAsync( @"[||]if ((/*1*/a/*2*/)) { a(); } else { b(); }", @"if (/*1*/!a/*2*/) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_DoubleParenthesesWithMiddleTrivia() { await TestFixOneAsync( @"[||]if (/*1*/(a)/*2*/) { a(); } else { b(); }", @"if (/*1*/!a/*2*/) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_DoubleParenthesesWithOutsideTrivia() { await TestFixOneAsync( @"[||]if /*before*/((a))/*after*/ { a(); } else { b(); }", @"if /*before*/(!a)/*after*/ { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Is() { await TestFixOneAsync( @"[||]if (a is Goo) { a(); } else { b(); }", @"if (a is not Goo) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_MethodCall() { await TestFixOneAsync( @"[||]if (a.Goo()) { a(); } else { b(); }", @"if (!a.Goo()) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Or() { await TestFixOneAsync( @"[||]if (a || b) { a(); } else { b(); }", @"if (!a && !b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Or2() { await TestFixOneAsync( @"[||]if (!a || !b) { a(); } else { b(); }", @"if (a && b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Or3() { await TestFixOneAsync( @"[||]if (!a || b) { a(); } else { b(); }", @"if (a && !b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Or4() { await TestFixOneAsync( @"[||]if (a | b) { a(); } else { b(); }", @"if (!a & !b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_And() { await TestFixOneAsync( @"[||]if (a && b) { a(); } else { b(); }", @"if (!a || !b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_And2() { await TestFixOneAsync( @"[||]if (!a && !b) { a(); } else { b(); }", @"if (a || b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_And3() { await TestFixOneAsync( @"[||]if (!a && b) { a(); } else { b(); }", @"if (a || !b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_And4() { await TestFixOneAsync( @"[||]if (a & b) { a(); } else { b(); }", @"if (!a | !b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_ParenthesizeAndForPrecedence() { await TestFixOneAsync( @"[||]if (a && b || c) { a(); } else { b(); }", @"if ((!a || !b) && !c) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Plus() { await TestFixOneAsync( @"[||]if (a + b) { a(); } else { b(); }", @"if (!(a + b)) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_True() { await TestFixOneAsync( @"[||]if (true) { a(); } else { b(); }", @"if (false) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_TrueWithTrivia() { await TestFixOneAsync( @"[||]if (/*1*/true/*2*/) { a(); } else { b(); }", @"if (/*1*/false/*2*/) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_False() { await TestFixOneAsync( @"[||]if (false) { a(); } else { b(); }", @"if (true) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_OtherLiteralExpression() { await TestFixOneAsync( @"[||]if (literalexpression) { a(); } else { b(); }", @"if (!literalexpression) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_TrueAndFalse() { await TestFixOneAsync( @"[||]if (true && false) { a(); } else { b(); }", @"if (false || true) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_NoCurlyBraces() { await TestFixOneAsync( @"[||]if (a) a(); else b();", @"if (!a) b(); else a();"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_CurlyBracesOnIf() { await TestFixOneAsync( @"[||]if (a) { a(); } else b();", @"if (!a) b(); else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_CurlyBracesOnElse() { await TestFixOneAsync( @"[||]if (a) a(); else { b(); }", @"if (!a) { b(); } else a();"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_IfElseIf() { await TestFixOneAsync( @"[||]if (a) { a(); } else if (b) { b(); }", @"if (!a) { if (b) { b(); } } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_IfElseIfElse() { await TestFixOneAsync( @"[||]if (a) { a(); } else if (b) { b(); } else { c(); }", @"if (!a) { if (b) { b(); } else { c(); } } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_CompoundConditional() { await TestFixOneAsync( @"[||]if (((a == b) && (c != d)) || ((e < f) && (!g))) { a(); } else { b(); }", @"if ((a != b || c == d) && (e >= f || g)) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Trivia() { await TestFixOneAsync( @"[||]if /*1*/ (a) /*2*/ { /*3*/ a() /*4*/; /*5*/ } /*6*/ else if /*7*/ (b) /*8*/ { /*9*/ b(); /*10*/ } /*11*/ else /*12*/ { /*13*/ c(); /*14*/} /*15*/", @"if /*1*/ (!a) /*2*/ { if /*7*/ (b) /*8*/ { /*9*/ b(); /*10*/ } /*11*/ else /*12*/ { /*13*/ c(); /*14*/} /*6*/ } else { /*3*/ a() /*4*/; /*5*/ } /*15*/"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestKeepTriviaWithinExpression_BrokenCode() { await TestInRegularAndScriptAsync( @"class A { void Goo() { [||]if (a || b && c < // comment d) { a(); } else { b(); } } }", @"class A { void Goo() { if (!a && (!b || c >= // comment d)) { b(); } else { a(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestKeepTriviaWithinExpression() { await TestInRegularAndScriptAsync( @"class A { void Goo() { bool a = true; bool b = true; bool c = true; bool d = true; [||]if (a || b && c < // comment d) { a(); } else { b(); } } }", @"class A { void Goo() { bool a = true; bool b = true; bool c = true; bool d = true; if (!a && (!b || c >= // comment d)) { b(); } else { a(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestMultiline_IfElseIfElse() { await TestInRegularAndScriptAsync( @"class A { void Goo() { [||]if (a) { a(); } else if (b) { b(); } else { c(); } } }", @"class A { void Goo() { if (!a) { if (b) { b(); } else { c(); } } else { a(); } } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestMultiline_IfElseIfElseSelection1() { await TestInRegularAndScriptAsync( @"class A { void Goo() { [|if (a) { a(); } else if (b) { b(); } else { c(); }|] } }", @"class A { void Goo() { if (!a) { if (b) { b(); } else { c(); } } else { a(); } } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestMultiline_IfElseIfElseSelection2() { await TestInRegularAndScriptAsync( @"class A { void Goo() { [|if (a) { a(); }|] else if (b) { b(); } else { c(); } } }", @"class A { void Goo() { if (!a) { if (b) { b(); } else { c(); } } else { a(); } } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestMultilineMissing_IfElseIfElseSubSelection() { await TestMissingInRegularAndScriptAsync( @"class A { void Goo() { if (a) { a(); } [|else if (b) { b(); } else { c(); }|] } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestMultiline_IfElse() { await TestInRegularAndScriptAsync( @"class A { void Goo() { [||]if (foo) bar(); else if (baz) Quux(); } }", @"class A { void Goo() { if (!foo) { if (baz) Quux(); } else bar(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestMultiline_OpenCloseBracesSameLine() { await TestInRegularAndScriptAsync( @"class A { void Goo() { [||]if (foo) { x(); x(); } else { y(); y(); } } }", @"class A { void Goo() { if (!foo) { y(); y(); } else { x(); x(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestMultiline_Trivia() { await TestInRegularAndScriptAsync( @"class A { void Goo() { /*1*/ [||]if (a) /*2*/ { /*3*/ /*4*/ goo(); /*5*/ /*6*/ } /*7*/ else if (b) /*8*/ { /*9*/ /*10*/ goo(); /*11*/ /*12*/ } /*13*/ else /*14*/ { /*15*/ /*16*/ goo(); /*17*/ /*18*/ } /*19*/ /*20*/ } }", @"class A { void Goo() { /*1*/ if (!a) /*2*/ { if (b) /*8*/ { /*9*/ /*10*/ goo(); /*11*/ /*12*/ } /*13*/ else /*14*/ { /*15*/ /*16*/ goo(); /*17*/ /*18*/ } /*19*/ } else { /*3*/ /*4*/ goo(); /*5*/ /*6*/ } /*7*/ /*20*/ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestOverlapsHiddenPosition1() { await TestMissingInRegularAndScriptAsync( @"class C { void F() { #line hidden [||]if (a) { a(); } else { b(); } #line default } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestOverlapsHiddenPosition2() { await TestMissingInRegularAndScriptAsync( @"class C { void F() { [||]if (a) { #line hidden a(); #line default } else { b(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestOverlapsHiddenPosition3() { await TestMissingInRegularAndScriptAsync( @"class C { void F() { [||]if (a) { a(); } else { #line hidden b(); #line default } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestOverlapsHiddenPosition4() { await TestMissingInRegularAndScriptAsync( @"class C { void F() { [||]if (a) { #line hidden a(); } else { b(); #line default } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestOverlapsHiddenPosition5() { await TestMissingInRegularAndScriptAsync( @"class C { void F() { [||]if (a) { a(); #line hidden } else { #line default b(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestOverlapsHiddenPosition6() { await TestInRegularAndScriptAsync( @" #line hidden class C { void F() { #line default [||]if (a) { a(); } else { b(); } } }", @" #line hidden class C { void F() { #line default if (!a) { b(); } else { a(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestOverlapsHiddenPosition7() { await TestInRegularAndScriptAsync( @" #line hidden class C { void F() { #line default [||]if (a) { a(); } else { b(); } #line hidden } } #line default", @" #line hidden class C { void F() { #line default if (!a) { b(); } else { a(); } #line hidden } } #line default"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToLengthEqualsZero() { await TestFixOneAsync( @"string x; [||]if (x.Length > 0) { GreaterThanZero(); } else { EqualsZero(); } } } ", @"string x; if (x.Length == 0) { EqualsZero(); } else { GreaterThanZero(); } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToLengthEqualsZero2() { await TestFixOneAsync( @"string[] x; [||]if (x.Length > 0) { GreaterThanZero(); } else { EqualsZero(); } } } ", @"string[] x; if (x.Length == 0) { EqualsZero(); } else { GreaterThanZero(); } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToLengthEqualsZero3() { await TestFixOneAsync( @"string x; [||]if (x.Length > 0x0) { a(); } else { b(); } } } ", @"string x; if (x.Length == 0x0) { b(); } else { a(); } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToLengthEqualsZero4() { await TestFixOneAsync( @"string x; [||]if (0 < x.Length) { a(); } else { b(); } } } ", @"string x; if (0 == x.Length) { b(); } else { a(); } } } "); } [WorkItem(545986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545986")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToEqualsZero1() { await TestFixOneAsync( @"byte x = 1; [||]if (0 < x) { a(); } else { b(); } } } ", @"byte x = 1; if (0 == x) { b(); } else { a(); } } } "); } [WorkItem(545986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545986")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToEqualsZero2() { await TestFixOneAsync( @"ushort x = 1; [||]if (0 < x) { a(); } else { b(); } } } ", @"ushort x = 1; if (0 == x) { b(); } else { a(); } } } "); } [WorkItem(545986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545986")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToEqualsZero3() { await TestFixOneAsync( @"uint x = 1; [||]if (0 < x) { a(); } else { b(); } } } ", @"uint x = 1; if (0 == x) { b(); } else { a(); } } } "); } [WorkItem(545986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545986")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToEqualsZero4() { await TestFixOneAsync( @"ulong x = 1; [||]if (x > 0) { a(); } else { b(); } } } ", @"ulong x = 1; if (x == 0) { b(); } else { a(); } } } "); } [WorkItem(545986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545986")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToNotEqualsZero1() { await TestFixOneAsync( @"ulong x = 1; [||]if (0 == x) { a(); } else { b(); } } } ", @"ulong x = 1; if (0 != x) { b(); } else { a(); } } } "); } [WorkItem(545986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545986")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToNotEqualsZero2() { await TestFixOneAsync( @"ulong x = 1; [||]if (x == 0) { a(); } else { b(); } } } ", @"ulong x = 1; if (x != 0) { b(); } else { a(); } } } "); } [WorkItem(530505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530505")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyLongLengthEqualsZero() { await TestFixOneAsync( @"string[] x; [||]if (x.LongLength > 0) { GreaterThanZero(); } else { EqualsZero(); } } } ", @"string[] x; if (x.LongLength == 0) { EqualsZero(); } else { GreaterThanZero(); } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_DoesNotSimplifyToLengthEqualsZero() { await TestFixOneAsync( @"string x; [||]if (x.Length >= 0) { a(); } else { b(); } } } ", @"string x; if (x.Length < 0) { b(); } else { a(); } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_DoesNotSimplifyToLengthEqualsZero2() { await TestFixOneAsync( @"string x; [||]if (x.Length > 0.0f) { GreaterThanZero(); } else { EqualsZero(); } } } ", @"string x; if (x.Length <= 0.0f) { EqualsZero(); } else { GreaterThanZero(); } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] [WorkItem(29434, "https://github.com/dotnet/roslyn/issues/29434")] public async Task TestIsExpression() { await TestInRegularAndScriptAsync( @"class C { void M(object o) { [||]if (o is C) { a(); } else { } } }", @"class C { void M(object o) { if (o is not C) { } else { a(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] [WorkItem(43224, "https://github.com/dotnet/roslyn/issues/43224")] public async Task TestEmptyIf() { await TestInRegularAndScriptAsync( @"class C { void M(string s){ [||]if (s == ""a""){}else{ s = ""b""}}}", @"class C { void M(string s){ if (s != ""a""){ s = ""b""}}}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] [WorkItem(43224, "https://github.com/dotnet/roslyn/issues/43224")] public async Task TestOnlySingleLineCommentIf() { await TestInRegularAndScriptAsync( @" class C { void M(string s) { [||]if (s == ""a"") { // A single line comment } else { s = ""b"" } } }", @" class C { void M(string s) { if (s != ""a"") { s = ""b"" } else { // A single line comment } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] [WorkItem(43224, "https://github.com/dotnet/roslyn/issues/43224")] public async Task TestOnlyMultilineLineCommentIf() { await TestInRegularAndScriptAsync( @" class C { void M(string s) { [||]if (s == ""a"") { /* * This is * a multiline * comment with * two words * per line. */ } else { s = ""b"" } } }", @" class C { void M(string s) { if (s != ""a"") { s = ""b"" } else { /* * This is * a multiline * comment with * two words * per line. */ } } }"); } } }
// Licensed to the .NET Foundation under one or more 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.InvertIf; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.InvertIf { public partial class InvertIfTests : AbstractCSharpCodeActionTest { private async Task TestFixOneAsync( string initial, string expected) { await TestInRegularAndScriptAsync(CreateTreeText(initial), CreateTreeText(expected)); } protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpInvertIfCodeRefactoringProvider(); private static string CreateTreeText(string initial) { return @"class A { bool a = true; bool b = true; bool c = true; bool d = true; void Goo() { " + initial + @" } }"; } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Identifier() { await TestFixOneAsync( @"[||]if (a) { a(); } else { b(); }", @"if (!a) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_IdentifierWithTrivia() { await TestFixOneAsync( @"[||]if /*0*/(/*1*/a/*2*/)/*3*/ { a(); } else { b(); }", @"if /*0*/(/*1*/!a/*2*/)/*3*/ { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_NotIdentifier() { await TestFixOneAsync( @"[||]if (!a) { a(); } else { b(); }", @"if (a) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_NotIdentifierWithTrivia() { await TestFixOneAsync( @"[||]if /*0*/(/*1*/!/*1b*/a/*2*/)/*3*/ { a(); } else { b(); }", @"if /*0*/(/*1*/a/*2*/)/*3*/ { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_EqualsEquals() { await TestFixOneAsync( @"[||]if (a == b) { a(); } else { b(); }", @"if (a != b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_NotEquals() { await TestFixOneAsync( @"[||]if (a != b) { a(); } else { b(); }", @"if (a == b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_GreaterThan() { await TestFixOneAsync( @"[||]if (a > b) { a(); } else { b(); }", @"if (a <= b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_GreaterThanEquals() { await TestFixOneAsync( @"[||]if (a >= b) { a(); } else { b(); }", @"if (a < b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_LessThan() { await TestFixOneAsync( @"[||]if (a < b) { a(); } else { b(); }", @"if (a >= b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_LessThanEquals() { await TestFixOneAsync( @"[||]if (a <= b) { a(); } else { b(); }", @"if (a > b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_DoubleParentheses() { await TestFixOneAsync( @"[||]if ((a)) { a(); } else { b(); }", @"if (!a) { b(); } else { a(); }"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/26427"), Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_DoubleParenthesesWithInnerTrivia() { await TestFixOneAsync( @"[||]if ((/*1*/a/*2*/)) { a(); } else { b(); }", @"if (/*1*/!a/*2*/) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_DoubleParenthesesWithMiddleTrivia() { await TestFixOneAsync( @"[||]if (/*1*/(a)/*2*/) { a(); } else { b(); }", @"if (/*1*/!a/*2*/) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_DoubleParenthesesWithOutsideTrivia() { await TestFixOneAsync( @"[||]if /*before*/((a))/*after*/ { a(); } else { b(); }", @"if /*before*/(!a)/*after*/ { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Is() { await TestFixOneAsync( @"[||]if (a is Goo) { a(); } else { b(); }", @"if (a is not Goo) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_MethodCall() { await TestFixOneAsync( @"[||]if (a.Goo()) { a(); } else { b(); }", @"if (!a.Goo()) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Or() { await TestFixOneAsync( @"[||]if (a || b) { a(); } else { b(); }", @"if (!a && !b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Or2() { await TestFixOneAsync( @"[||]if (!a || !b) { a(); } else { b(); }", @"if (a && b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Or3() { await TestFixOneAsync( @"[||]if (!a || b) { a(); } else { b(); }", @"if (a && !b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Or4() { await TestFixOneAsync( @"[||]if (a | b) { a(); } else { b(); }", @"if (!a & !b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_And() { await TestFixOneAsync( @"[||]if (a && b) { a(); } else { b(); }", @"if (!a || !b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_And2() { await TestFixOneAsync( @"[||]if (!a && !b) { a(); } else { b(); }", @"if (a || b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_And3() { await TestFixOneAsync( @"[||]if (!a && b) { a(); } else { b(); }", @"if (a || !b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_And4() { await TestFixOneAsync( @"[||]if (a & b) { a(); } else { b(); }", @"if (!a | !b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_ParenthesizeAndForPrecedence() { await TestFixOneAsync( @"[||]if (a && b || c) { a(); } else { b(); }", @"if ((!a || !b) && !c) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Plus() { await TestFixOneAsync( @"[||]if (a + b) { a(); } else { b(); }", @"if (!(a + b)) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_True() { await TestFixOneAsync( @"[||]if (true) { a(); } else { b(); }", @"if (false) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_TrueWithTrivia() { await TestFixOneAsync( @"[||]if (/*1*/true/*2*/) { a(); } else { b(); }", @"if (/*1*/false/*2*/) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_False() { await TestFixOneAsync( @"[||]if (false) { a(); } else { b(); }", @"if (true) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_OtherLiteralExpression() { await TestFixOneAsync( @"[||]if (literalexpression) { a(); } else { b(); }", @"if (!literalexpression) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_TrueAndFalse() { await TestFixOneAsync( @"[||]if (true && false) { a(); } else { b(); }", @"if (false || true) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_NoCurlyBraces() { await TestFixOneAsync( @"[||]if (a) a(); else b();", @"if (!a) b(); else a();"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_CurlyBracesOnIf() { await TestFixOneAsync( @"[||]if (a) { a(); } else b();", @"if (!a) b(); else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_CurlyBracesOnElse() { await TestFixOneAsync( @"[||]if (a) a(); else { b(); }", @"if (!a) { b(); } else a();"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_IfElseIf() { await TestFixOneAsync( @"[||]if (a) { a(); } else if (b) { b(); }", @"if (!a) { if (b) { b(); } } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_IfElseIfElse() { await TestFixOneAsync( @"[||]if (a) { a(); } else if (b) { b(); } else { c(); }", @"if (!a) { if (b) { b(); } else { c(); } } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_CompoundConditional() { await TestFixOneAsync( @"[||]if (((a == b) && (c != d)) || ((e < f) && (!g))) { a(); } else { b(); }", @"if ((a != b || c == d) && (e >= f || g)) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Trivia() { await TestFixOneAsync( @"[||]if /*1*/ (a) /*2*/ { /*3*/ a() /*4*/; /*5*/ } /*6*/ else if /*7*/ (b) /*8*/ { /*9*/ b(); /*10*/ } /*11*/ else /*12*/ { /*13*/ c(); /*14*/} /*15*/", @"if /*1*/ (!a) /*2*/ { if /*7*/ (b) /*8*/ { /*9*/ b(); /*10*/ } /*11*/ else /*12*/ { /*13*/ c(); /*14*/} /*6*/ } else { /*3*/ a() /*4*/; /*5*/ } /*15*/"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestKeepTriviaWithinExpression_BrokenCode() { await TestInRegularAndScriptAsync( @"class A { void Goo() { [||]if (a || b && c < // comment d) { a(); } else { b(); } } }", @"class A { void Goo() { if (!a && (!b || c >= // comment d)) { b(); } else { a(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestKeepTriviaWithinExpression() { await TestInRegularAndScriptAsync( @"class A { void Goo() { bool a = true; bool b = true; bool c = true; bool d = true; [||]if (a || b && c < // comment d) { a(); } else { b(); } } }", @"class A { void Goo() { bool a = true; bool b = true; bool c = true; bool d = true; if (!a && (!b || c >= // comment d)) { b(); } else { a(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestMultiline_IfElseIfElse() { await TestInRegularAndScriptAsync( @"class A { void Goo() { [||]if (a) { a(); } else if (b) { b(); } else { c(); } } }", @"class A { void Goo() { if (!a) { if (b) { b(); } else { c(); } } else { a(); } } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestMultiline_IfElseIfElseSelection1() { await TestInRegularAndScriptAsync( @"class A { void Goo() { [|if (a) { a(); } else if (b) { b(); } else { c(); }|] } }", @"class A { void Goo() { if (!a) { if (b) { b(); } else { c(); } } else { a(); } } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestMultiline_IfElseIfElseSelection2() { await TestInRegularAndScriptAsync( @"class A { void Goo() { [|if (a) { a(); }|] else if (b) { b(); } else { c(); } } }", @"class A { void Goo() { if (!a) { if (b) { b(); } else { c(); } } else { a(); } } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestMultilineMissing_IfElseIfElseSubSelection() { await TestMissingInRegularAndScriptAsync( @"class A { void Goo() { if (a) { a(); } [|else if (b) { b(); } else { c(); }|] } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestMultiline_IfElse() { await TestInRegularAndScriptAsync( @"class A { void Goo() { [||]if (foo) bar(); else if (baz) Quux(); } }", @"class A { void Goo() { if (!foo) { if (baz) Quux(); } else bar(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestMultiline_OpenCloseBracesSameLine() { await TestInRegularAndScriptAsync( @"class A { void Goo() { [||]if (foo) { x(); x(); } else { y(); y(); } } }", @"class A { void Goo() { if (!foo) { y(); y(); } else { x(); x(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestMultiline_Trivia() { await TestInRegularAndScriptAsync( @"class A { void Goo() { /*1*/ [||]if (a) /*2*/ { /*3*/ /*4*/ goo(); /*5*/ /*6*/ } /*7*/ else if (b) /*8*/ { /*9*/ /*10*/ goo(); /*11*/ /*12*/ } /*13*/ else /*14*/ { /*15*/ /*16*/ goo(); /*17*/ /*18*/ } /*19*/ /*20*/ } }", @"class A { void Goo() { /*1*/ if (!a) /*2*/ { if (b) /*8*/ { /*9*/ /*10*/ goo(); /*11*/ /*12*/ } /*13*/ else /*14*/ { /*15*/ /*16*/ goo(); /*17*/ /*18*/ } /*19*/ } else { /*3*/ /*4*/ goo(); /*5*/ /*6*/ } /*7*/ /*20*/ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestOverlapsHiddenPosition1() { await TestMissingInRegularAndScriptAsync( @"class C { void F() { #line hidden [||]if (a) { a(); } else { b(); } #line default } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestOverlapsHiddenPosition2() { await TestMissingInRegularAndScriptAsync( @"class C { void F() { [||]if (a) { #line hidden a(); #line default } else { b(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestOverlapsHiddenPosition3() { await TestMissingInRegularAndScriptAsync( @"class C { void F() { [||]if (a) { a(); } else { #line hidden b(); #line default } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestOverlapsHiddenPosition4() { await TestMissingInRegularAndScriptAsync( @"class C { void F() { [||]if (a) { #line hidden a(); } else { b(); #line default } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestOverlapsHiddenPosition5() { await TestMissingInRegularAndScriptAsync( @"class C { void F() { [||]if (a) { a(); #line hidden } else { #line default b(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestOverlapsHiddenPosition6() { await TestInRegularAndScriptAsync( @" #line hidden class C { void F() { #line default [||]if (a) { a(); } else { b(); } } }", @" #line hidden class C { void F() { #line default if (!a) { b(); } else { a(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestOverlapsHiddenPosition7() { await TestInRegularAndScriptAsync( @" #line hidden class C { void F() { #line default [||]if (a) { a(); } else { b(); } #line hidden } } #line default", @" #line hidden class C { void F() { #line default if (!a) { b(); } else { a(); } #line hidden } } #line default"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToLengthEqualsZero() { await TestFixOneAsync( @"string x; [||]if (x.Length > 0) { GreaterThanZero(); } else { EqualsZero(); } } } ", @"string x; if (x.Length == 0) { EqualsZero(); } else { GreaterThanZero(); } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToLengthEqualsZero2() { await TestFixOneAsync( @"string[] x; [||]if (x.Length > 0) { GreaterThanZero(); } else { EqualsZero(); } } } ", @"string[] x; if (x.Length == 0) { EqualsZero(); } else { GreaterThanZero(); } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToLengthEqualsZero3() { await TestFixOneAsync( @"string x; [||]if (x.Length > 0x0) { a(); } else { b(); } } } ", @"string x; if (x.Length == 0x0) { b(); } else { a(); } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToLengthEqualsZero4() { await TestFixOneAsync( @"string x; [||]if (0 < x.Length) { a(); } else { b(); } } } ", @"string x; if (0 == x.Length) { b(); } else { a(); } } } "); } [WorkItem(545986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545986")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToEqualsZero1() { await TestFixOneAsync( @"byte x = 1; [||]if (0 < x) { a(); } else { b(); } } } ", @"byte x = 1; if (0 == x) { b(); } else { a(); } } } "); } [WorkItem(545986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545986")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToEqualsZero2() { await TestFixOneAsync( @"ushort x = 1; [||]if (0 < x) { a(); } else { b(); } } } ", @"ushort x = 1; if (0 == x) { b(); } else { a(); } } } "); } [WorkItem(545986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545986")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToEqualsZero3() { await TestFixOneAsync( @"uint x = 1; [||]if (0 < x) { a(); } else { b(); } } } ", @"uint x = 1; if (0 == x) { b(); } else { a(); } } } "); } [WorkItem(545986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545986")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToEqualsZero4() { await TestFixOneAsync( @"ulong x = 1; [||]if (x > 0) { a(); } else { b(); } } } ", @"ulong x = 1; if (x == 0) { b(); } else { a(); } } } "); } [WorkItem(545986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545986")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToNotEqualsZero1() { await TestFixOneAsync( @"ulong x = 1; [||]if (0 == x) { a(); } else { b(); } } } ", @"ulong x = 1; if (0 != x) { b(); } else { a(); } } } "); } [WorkItem(545986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545986")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToNotEqualsZero2() { await TestFixOneAsync( @"ulong x = 1; [||]if (x == 0) { a(); } else { b(); } } } ", @"ulong x = 1; if (x != 0) { b(); } else { a(); } } } "); } [WorkItem(530505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530505")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyLongLengthEqualsZero() { await TestFixOneAsync( @"string[] x; [||]if (x.LongLength > 0) { GreaterThanZero(); } else { EqualsZero(); } } } ", @"string[] x; if (x.LongLength == 0) { EqualsZero(); } else { GreaterThanZero(); } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_DoesNotSimplifyToLengthEqualsZero() { await TestFixOneAsync( @"string x; [||]if (x.Length >= 0) { a(); } else { b(); } } } ", @"string x; if (x.Length < 0) { b(); } else { a(); } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_DoesNotSimplifyToLengthEqualsZero2() { await TestFixOneAsync( @"string x; [||]if (x.Length > 0.0f) { GreaterThanZero(); } else { EqualsZero(); } } } ", @"string x; if (x.Length <= 0.0f) { EqualsZero(); } else { GreaterThanZero(); } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] [WorkItem(29434, "https://github.com/dotnet/roslyn/issues/29434")] public async Task TestIsExpression() { await TestInRegularAndScriptAsync( @"class C { void M(object o) { [||]if (o is C) { a(); } else { } } }", @"class C { void M(object o) { if (o is not C) { } else { a(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] [WorkItem(43224, "https://github.com/dotnet/roslyn/issues/43224")] public async Task TestEmptyIf() { await TestInRegularAndScriptAsync( @"class C { void M(string s){ [||]if (s == ""a""){}else{ s = ""b""}}}", @"class C { void M(string s){ if (s != ""a""){ s = ""b""}}}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] [WorkItem(43224, "https://github.com/dotnet/roslyn/issues/43224")] public async Task TestOnlySingleLineCommentIf() { await TestInRegularAndScriptAsync( @" class C { void M(string s) { [||]if (s == ""a"") { // A single line comment } else { s = ""b"" } } }", @" class C { void M(string s) { if (s != ""a"") { s = ""b"" } else { // A single line comment } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] [WorkItem(43224, "https://github.com/dotnet/roslyn/issues/43224")] public async Task TestOnlyMultilineLineCommentIf() { await TestInRegularAndScriptAsync( @" class C { void M(string s) { [||]if (s == ""a"") { /* * This is * a multiline * comment with * two words * per line. */ } else { s = ""b"" } } }", @" class C { void M(string s) { if (s != ""a"") { s = ""b"" } else { /* * This is * a multiline * comment with * two words * per line. */ } } }"); } } }
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/DiagnosticAnalyzer/CompilerDiagnosticAnalyzer.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.Diagnostics { /// <summary> /// DiagnosticAnalyzer for compiler's syntax/semantic/compilation diagnostics. /// </summary> internal abstract partial class CompilerDiagnosticAnalyzer : DiagnosticAnalyzer { internal abstract CommonMessageProvider MessageProvider { get; } internal abstract ImmutableArray<int> GetSupportedErrorCodes(); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { // DiagnosticAnalyzer.SupportedDiagnostics should be invoked only once per analyzer, // so we don't need to store the computed descriptors array into a field. var messageProvider = this.MessageProvider; var errorCodes = this.GetSupportedErrorCodes(); var builder = ImmutableArray.CreateBuilder<DiagnosticDescriptor>(errorCodes.Length); foreach (var errorCode in errorCodes) { var descriptor = DiagnosticInfo.GetDescriptor(errorCode, messageProvider); builder.Add(descriptor); } builder.Add(AnalyzerExecutor.GetAnalyzerExceptionDiagnosticDescriptor()); return builder.ToImmutable(); } } public sealed override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); context.RegisterCompilationStartAction(c => { var analyzer = new CompilationAnalyzer(c.Compilation); c.RegisterSyntaxTreeAction(analyzer.AnalyzeSyntaxTree); c.RegisterSemanticModelAction(CompilationAnalyzer.AnalyzeSemanticModel); }); } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics { /// <summary> /// DiagnosticAnalyzer for compiler's syntax/semantic/compilation diagnostics. /// </summary> internal abstract partial class CompilerDiagnosticAnalyzer : DiagnosticAnalyzer { internal abstract CommonMessageProvider MessageProvider { get; } internal abstract ImmutableArray<int> GetSupportedErrorCodes(); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { // DiagnosticAnalyzer.SupportedDiagnostics should be invoked only once per analyzer, // so we don't need to store the computed descriptors array into a field. var messageProvider = this.MessageProvider; var errorCodes = this.GetSupportedErrorCodes(); var builder = ImmutableArray.CreateBuilder<DiagnosticDescriptor>(errorCodes.Length); foreach (var errorCode in errorCodes) { var descriptor = DiagnosticInfo.GetDescriptor(errorCode, messageProvider); builder.Add(descriptor); } builder.Add(AnalyzerExecutor.GetAnalyzerExceptionDiagnosticDescriptor()); return builder.ToImmutable(); } } public sealed override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); context.RegisterCompilationStartAction(c => { var analyzer = new CompilationAnalyzer(c.Compilation); c.RegisterSyntaxTreeAction(analyzer.AnalyzeSyntaxTree); c.RegisterSemanticModelAction(CompilationAnalyzer.AnalyzeSemanticModel); }); } } }
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractUnncessarySuppressionDiagnosticTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions; using Microsoft.CodeAnalysis.UnitTests.Diagnostics; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics { public abstract class AbstractUnncessarySuppressionDiagnosticTest : AbstractUserDiagnosticTest { protected AbstractUnncessarySuppressionDiagnosticTest(ITestOutputHelper logger) : base(logger) { } internal abstract CodeFixProvider CodeFixProvider { get; } internal abstract AbstractRemoveUnnecessaryInlineSuppressionsDiagnosticAnalyzer SuppressionAnalyzer { get; } internal abstract ImmutableArray<DiagnosticAnalyzer> OtherAnalyzers { get; } private void AddAnalyzersToWorkspace(TestWorkspace workspace) { var analyzerReference = new AnalyzerImageReference(OtherAnalyzers.Add(SuppressionAnalyzer)); workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference })); } internal override async Task<IEnumerable<Diagnostic>> GetDiagnosticsAsync( TestWorkspace workspace, TestParameters parameters) { AddAnalyzersToWorkspace(workspace); var document = GetDocumentAndSelectSpan(workspace, out var span); return await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(workspace, document, span); } internal override async Task<(ImmutableArray<Diagnostic>, ImmutableArray<CodeAction>, CodeAction actionToInvoke)> GetDiagnosticAndFixesAsync( TestWorkspace workspace, TestParameters parameters) { AddAnalyzersToWorkspace(workspace); string annotation = null; if (!TryGetDocumentAndSelectSpan(workspace, out var document, out var span)) { document = GetDocumentAndAnnotatedSpan(workspace, out annotation, out span); } // Include suppressed diagnostics as they are needed by unnecessary suppressions analyzer. var testDriver = new TestDiagnosticAnalyzerDriver(workspace, document.Project, includeSuppressedDiagnostics: true); var diagnostics = await testDriver.GetAllDiagnosticsAsync(document, span); // Filter out suppressed diagnostics before invoking code fix. diagnostics = diagnostics.Where(d => !d.IsSuppressed); return await GetDiagnosticAndFixesAsync( diagnostics, CodeFixProvider, testDriver, document, span, annotation, parameters.index); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions; using Microsoft.CodeAnalysis.UnitTests.Diagnostics; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics { public abstract class AbstractUnncessarySuppressionDiagnosticTest : AbstractUserDiagnosticTest { protected AbstractUnncessarySuppressionDiagnosticTest(ITestOutputHelper logger) : base(logger) { } internal abstract CodeFixProvider CodeFixProvider { get; } internal abstract AbstractRemoveUnnecessaryInlineSuppressionsDiagnosticAnalyzer SuppressionAnalyzer { get; } internal abstract ImmutableArray<DiagnosticAnalyzer> OtherAnalyzers { get; } private void AddAnalyzersToWorkspace(TestWorkspace workspace) { var analyzerReference = new AnalyzerImageReference(OtherAnalyzers.Add(SuppressionAnalyzer)); workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference })); } internal override async Task<IEnumerable<Diagnostic>> GetDiagnosticsAsync( TestWorkspace workspace, TestParameters parameters) { AddAnalyzersToWorkspace(workspace); var document = GetDocumentAndSelectSpan(workspace, out var span); return await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(workspace, document, span); } internal override async Task<(ImmutableArray<Diagnostic>, ImmutableArray<CodeAction>, CodeAction actionToInvoke)> GetDiagnosticAndFixesAsync( TestWorkspace workspace, TestParameters parameters) { AddAnalyzersToWorkspace(workspace); string annotation = null; if (!TryGetDocumentAndSelectSpan(workspace, out var document, out var span)) { document = GetDocumentAndAnnotatedSpan(workspace, out annotation, out span); } // Include suppressed diagnostics as they are needed by unnecessary suppressions analyzer. var testDriver = new TestDiagnosticAnalyzerDriver(workspace, document.Project, includeSuppressedDiagnostics: true); var diagnostics = await testDriver.GetAllDiagnosticsAsync(document, span); // Filter out suppressed diagnostics before invoking code fix. diagnostics = diagnostics.Where(d => !d.IsSuppressed); return await GetDiagnosticAndFixesAsync( diagnostics, CodeFixProvider, testDriver, document, span, annotation, parameters.index); } } }
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_DelegateCreation.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.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitDelegateCreationExpression(node As BoundDelegateCreationExpression) As BoundNode ' if there is a stub needed because of a delegate relaxation, the DelegateCreationNode has ' it stored in RelaxationLambdaOpt. ' The lambda rewriter will then take care of the code generation later on. If node.RelaxationLambdaOpt Is Nothing Then Debug.Assert(node.RelaxationReceiverPlaceholderOpt Is Nothing OrElse Me._inExpressionLambda) Return MyBase.VisitDelegateCreationExpression(node) Else Dim placeholderOpt As BoundRValuePlaceholder = node.RelaxationReceiverPlaceholderOpt Dim captureTemp As SynthesizedLocal = Nothing If placeholderOpt IsNot Nothing Then If Me._inExpressionLambda Then Me.AddPlaceholderReplacement(placeholderOpt, VisitExpression(node.ReceiverOpt)) Else captureTemp = New SynthesizedLocal(Me._currentMethodOrLambda, placeholderOpt.Type, SynthesizedLocalKind.DelegateRelaxationReceiver, syntaxOpt:=placeholderOpt.Syntax) Dim actualReceiver = New BoundLocal(placeholderOpt.Syntax, captureTemp, captureTemp.Type).MakeRValue Me.AddPlaceholderReplacement(placeholderOpt, actualReceiver) End If End If Dim relaxationLambda = DirectCast(Me.Visit(node.RelaxationLambdaOpt), BoundLambda) If placeholderOpt IsNot Nothing Then Me.RemovePlaceholderReplacement(placeholderOpt) End If Dim result As BoundExpression = New BoundConversion( relaxationLambda.Syntax, relaxationLambda, ConversionKind.Lambda Or ConversionKind.Widening, checked:=False, explicitCastInCode:=False, Type:=node.Type, hasErrors:=node.HasErrors) If captureTemp IsNot Nothing Then Dim receiverToCapture As BoundExpression = VisitExpressionNode(node.ReceiverOpt) Dim capture = New BoundAssignmentOperator(receiverToCapture.Syntax, New BoundLocal(receiverToCapture.Syntax, captureTemp, captureTemp.Type), receiverToCapture.MakeRValue(), suppressObjectClone:=True, Type:=captureTemp.Type) result = New BoundSequence( result.Syntax, ImmutableArray.Create(Of LocalSymbol)(captureTemp), ImmutableArray.Create(Of BoundExpression)(capture), result, result.Type) End If Return result End If 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.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitDelegateCreationExpression(node As BoundDelegateCreationExpression) As BoundNode ' if there is a stub needed because of a delegate relaxation, the DelegateCreationNode has ' it stored in RelaxationLambdaOpt. ' The lambda rewriter will then take care of the code generation later on. If node.RelaxationLambdaOpt Is Nothing Then Debug.Assert(node.RelaxationReceiverPlaceholderOpt Is Nothing OrElse Me._inExpressionLambda) Return MyBase.VisitDelegateCreationExpression(node) Else Dim placeholderOpt As BoundRValuePlaceholder = node.RelaxationReceiverPlaceholderOpt Dim captureTemp As SynthesizedLocal = Nothing If placeholderOpt IsNot Nothing Then If Me._inExpressionLambda Then Me.AddPlaceholderReplacement(placeholderOpt, VisitExpression(node.ReceiverOpt)) Else captureTemp = New SynthesizedLocal(Me._currentMethodOrLambda, placeholderOpt.Type, SynthesizedLocalKind.DelegateRelaxationReceiver, syntaxOpt:=placeholderOpt.Syntax) Dim actualReceiver = New BoundLocal(placeholderOpt.Syntax, captureTemp, captureTemp.Type).MakeRValue Me.AddPlaceholderReplacement(placeholderOpt, actualReceiver) End If End If Dim relaxationLambda = DirectCast(Me.Visit(node.RelaxationLambdaOpt), BoundLambda) If placeholderOpt IsNot Nothing Then Me.RemovePlaceholderReplacement(placeholderOpt) End If Dim result As BoundExpression = New BoundConversion( relaxationLambda.Syntax, relaxationLambda, ConversionKind.Lambda Or ConversionKind.Widening, checked:=False, explicitCastInCode:=False, Type:=node.Type, hasErrors:=node.HasErrors) If captureTemp IsNot Nothing Then Dim receiverToCapture As BoundExpression = VisitExpressionNode(node.ReceiverOpt) Dim capture = New BoundAssignmentOperator(receiverToCapture.Syntax, New BoundLocal(receiverToCapture.Syntax, captureTemp, captureTemp.Type), receiverToCapture.MakeRValue(), suppressObjectClone:=True, Type:=captureTemp.Type) result = New BoundSequence( result.Syntax, ImmutableArray.Create(Of LocalSymbol)(captureTemp), ImmutableArray.Create(Of BoundExpression)(capture), result, result.Type) End If Return result End If End Function End Class End Namespace
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/ExtractMethod/SelectionValidator.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractMethod { internal abstract partial class SelectionValidator { protected static readonly SelectionResult NullSelection = new NullSelectionResult(); protected readonly SemanticDocument SemanticDocument; protected readonly TextSpan OriginalSpan; protected readonly OptionSet Options; protected SelectionValidator( SemanticDocument document, TextSpan textSpan, OptionSet options) { Contract.ThrowIfNull(document); SemanticDocument = document; OriginalSpan = textSpan; Options = options; } public bool ContainsValidSelection { get { return !OriginalSpan.IsEmpty; } } public abstract Task<SelectionResult> GetValidSelectionAsync(CancellationToken cancellationToken); public abstract IEnumerable<SyntaxNode> GetOuterReturnStatements(SyntaxNode commonRoot, IEnumerable<SyntaxNode> jumpsOutOfRegion); public abstract bool IsFinalSpanSemanticallyValidSpan(SyntaxNode node, TextSpan textSpan, IEnumerable<SyntaxNode> returnStatements, CancellationToken cancellationToken); public abstract bool ContainsNonReturnExitPointsStatements(IEnumerable<SyntaxNode> jumpsOutOfRegion); protected bool IsFinalSpanSemanticallyValidSpan( SemanticModel semanticModel, TextSpan textSpan, Tuple<SyntaxNode, SyntaxNode> range, CancellationToken cancellationToken) { Contract.ThrowIfNull(range); var controlFlowAnalysisData = semanticModel.AnalyzeControlFlow(range.Item1, range.Item2); // there must be no control in and out of given span if (controlFlowAnalysisData.EntryPoints.Any()) { return false; } // check something like continue, break, yield break, yield return, and etc if (ContainsNonReturnExitPointsStatements(controlFlowAnalysisData.ExitPoints)) { return false; } // okay, there is no branch out, check whether next statement can be executed normally var returnStatements = GetOuterReturnStatements(range.Item1.GetCommonRoot(range.Item2), controlFlowAnalysisData.ExitPoints); if (!returnStatements.Any()) { if (!controlFlowAnalysisData.EndPointIsReachable) { // REVIEW: should we just do extract method regardless or show some warning to user? // in dev10, looks like we went ahead and did the extract method even if selection contains // unreachable code. } return true; } // okay, only branch was return. make sure we have all return in the selection. // check for special case, if end point is not reachable, we don't care the selection // actually contains all return statements. we just let extract method go through // and work like we did in dev10 if (!controlFlowAnalysisData.EndPointIsReachable) { return true; } // there is a return statement, and current position is reachable. let's check whether this is a case where that is okay return IsFinalSpanSemanticallyValidSpan(semanticModel.SyntaxTree.GetRoot(cancellationToken), textSpan, returnStatements, cancellationToken); } protected static Tuple<SyntaxNode, SyntaxNode> GetStatementRangeContainingSpan<T>( SyntaxNode root, TextSpan textSpan, CancellationToken cancellationToken) where T : SyntaxNode { // use top-down approach to find smallest statement range that contains given span. // this approach is more expansive than bottom-up approach I used before but way simpler and easy to understand var token1 = root.FindToken(textSpan.Start); var token2 = root.FindTokenFromEnd(textSpan.End); var commonRoot = token1.GetCommonRoot(token2).GetAncestorOrThis<T>() ?? root; var firstStatement = (T)null; var lastStatement = (T)null; var spine = new List<T>(); foreach (var stmt in commonRoot.DescendantNodesAndSelf().OfType<T>()) { cancellationToken.ThrowIfCancellationRequested(); // quick skip check. // - not containing at all if (stmt.Span.End < textSpan.Start) { continue; } // quick exit check // - passed candidate statements if (textSpan.End < stmt.SpanStart) { break; } if (stmt.SpanStart <= textSpan.Start) { // keep track spine spine.Add(stmt); } if (textSpan.End <= stmt.Span.End && spine.Any(s => s.Parent == stmt.Parent)) { // malformed code or selection can make spine to have more than an elements firstStatement = spine.First(s => s.Parent == stmt.Parent); lastStatement = stmt; spine.Clear(); } } if (firstStatement == null || lastStatement == null) { return null; } return new Tuple<SyntaxNode, SyntaxNode>(firstStatement, lastStatement); } protected static Tuple<SyntaxNode, SyntaxNode> GetStatementRangeContainedInSpan<T>( SyntaxNode root, TextSpan textSpan, CancellationToken cancellationToken) where T : SyntaxNode { // use top-down approach to find largest statement range contained in the given span // this method is a bit more expensive than bottom-up approach, but way more simpler than the other approach. var token1 = root.FindToken(textSpan.Start); var token2 = root.FindTokenFromEnd(textSpan.End); var commonRoot = token1.GetCommonRoot(token2).GetAncestorOrThis<T>() ?? root; T firstStatement = null; T lastStatement = null; foreach (var stmt in commonRoot.DescendantNodesAndSelf().OfType<T>()) { cancellationToken.ThrowIfCancellationRequested(); if (firstStatement == null && stmt.SpanStart >= textSpan.Start) { firstStatement = stmt; } if (firstStatement != null && stmt.Span.End <= textSpan.End && stmt.Parent == firstStatement.Parent) { lastStatement = stmt; } } if (firstStatement == null || lastStatement == null) { return null; } return new Tuple<SyntaxNode, SyntaxNode>(firstStatement, lastStatement); } } }
// Licensed to the .NET Foundation under one or more 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractMethod { internal abstract partial class SelectionValidator { protected static readonly SelectionResult NullSelection = new NullSelectionResult(); protected readonly SemanticDocument SemanticDocument; protected readonly TextSpan OriginalSpan; protected readonly OptionSet Options; protected SelectionValidator( SemanticDocument document, TextSpan textSpan, OptionSet options) { Contract.ThrowIfNull(document); SemanticDocument = document; OriginalSpan = textSpan; Options = options; } public bool ContainsValidSelection { get { return !OriginalSpan.IsEmpty; } } public abstract Task<SelectionResult> GetValidSelectionAsync(CancellationToken cancellationToken); public abstract IEnumerable<SyntaxNode> GetOuterReturnStatements(SyntaxNode commonRoot, IEnumerable<SyntaxNode> jumpsOutOfRegion); public abstract bool IsFinalSpanSemanticallyValidSpan(SyntaxNode node, TextSpan textSpan, IEnumerable<SyntaxNode> returnStatements, CancellationToken cancellationToken); public abstract bool ContainsNonReturnExitPointsStatements(IEnumerable<SyntaxNode> jumpsOutOfRegion); protected bool IsFinalSpanSemanticallyValidSpan( SemanticModel semanticModel, TextSpan textSpan, Tuple<SyntaxNode, SyntaxNode> range, CancellationToken cancellationToken) { Contract.ThrowIfNull(range); var controlFlowAnalysisData = semanticModel.AnalyzeControlFlow(range.Item1, range.Item2); // there must be no control in and out of given span if (controlFlowAnalysisData.EntryPoints.Any()) { return false; } // check something like continue, break, yield break, yield return, and etc if (ContainsNonReturnExitPointsStatements(controlFlowAnalysisData.ExitPoints)) { return false; } // okay, there is no branch out, check whether next statement can be executed normally var returnStatements = GetOuterReturnStatements(range.Item1.GetCommonRoot(range.Item2), controlFlowAnalysisData.ExitPoints); if (!returnStatements.Any()) { if (!controlFlowAnalysisData.EndPointIsReachable) { // REVIEW: should we just do extract method regardless or show some warning to user? // in dev10, looks like we went ahead and did the extract method even if selection contains // unreachable code. } return true; } // okay, only branch was return. make sure we have all return in the selection. // check for special case, if end point is not reachable, we don't care the selection // actually contains all return statements. we just let extract method go through // and work like we did in dev10 if (!controlFlowAnalysisData.EndPointIsReachable) { return true; } // there is a return statement, and current position is reachable. let's check whether this is a case where that is okay return IsFinalSpanSemanticallyValidSpan(semanticModel.SyntaxTree.GetRoot(cancellationToken), textSpan, returnStatements, cancellationToken); } protected static Tuple<SyntaxNode, SyntaxNode> GetStatementRangeContainingSpan<T>( SyntaxNode root, TextSpan textSpan, CancellationToken cancellationToken) where T : SyntaxNode { // use top-down approach to find smallest statement range that contains given span. // this approach is more expansive than bottom-up approach I used before but way simpler and easy to understand var token1 = root.FindToken(textSpan.Start); var token2 = root.FindTokenFromEnd(textSpan.End); var commonRoot = token1.GetCommonRoot(token2).GetAncestorOrThis<T>() ?? root; var firstStatement = (T)null; var lastStatement = (T)null; var spine = new List<T>(); foreach (var stmt in commonRoot.DescendantNodesAndSelf().OfType<T>()) { cancellationToken.ThrowIfCancellationRequested(); // quick skip check. // - not containing at all if (stmt.Span.End < textSpan.Start) { continue; } // quick exit check // - passed candidate statements if (textSpan.End < stmt.SpanStart) { break; } if (stmt.SpanStart <= textSpan.Start) { // keep track spine spine.Add(stmt); } if (textSpan.End <= stmt.Span.End && spine.Any(s => s.Parent == stmt.Parent)) { // malformed code or selection can make spine to have more than an elements firstStatement = spine.First(s => s.Parent == stmt.Parent); lastStatement = stmt; spine.Clear(); } } if (firstStatement == null || lastStatement == null) { return null; } return new Tuple<SyntaxNode, SyntaxNode>(firstStatement, lastStatement); } protected static Tuple<SyntaxNode, SyntaxNode> GetStatementRangeContainedInSpan<T>( SyntaxNode root, TextSpan textSpan, CancellationToken cancellationToken) where T : SyntaxNode { // use top-down approach to find largest statement range contained in the given span // this method is a bit more expensive than bottom-up approach, but way more simpler than the other approach. var token1 = root.FindToken(textSpan.Start); var token2 = root.FindTokenFromEnd(textSpan.End); var commonRoot = token1.GetCommonRoot(token2).GetAncestorOrThis<T>() ?? root; T firstStatement = null; T lastStatement = null; foreach (var stmt in commonRoot.DescendantNodesAndSelf().OfType<T>()) { cancellationToken.ThrowIfCancellationRequested(); if (firstStatement == null && stmt.SpanStart >= textSpan.Start) { firstStatement = stmt; } if (firstStatement != null && stmt.Span.End <= textSpan.End && stmt.Parent == firstStatement.Parent) { lastStatement = stmt; } } if (firstStatement == null || lastStatement == null) { return null; } return new Tuple<SyntaxNode, SyntaxNode>(firstStatement, lastStatement); } } }
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Test/Resources/Core/MetadataTests/InterfaceAndClass/CSClasses01.dll
MZ@ !L!This program cannot be run in DOS mode. $PELxN! ' @@ @'W@`  H.text  `.rsrc@ @@.reloc `@B'HT!@0 { +*&}*0 { +*&}*( *6rp( *6rp( *6r1p( *0rMp( o +*0rcp( o +*0ryp( o +*( *BSJB v4.0.30319l#~ #Strings#US#GUID#BlobW %3   LE b& n& & E? lLLE&/&s P xh t    " * 3: J R !YJ! )19fA Ip x..# a a ak|u<Sjl<Module>CSClasses01.dllICSPropImplMetadataICSGenImpl`2mscorlibSystemObjectCSInterfaces01ICSPropTVEFooefooget_ReadOnlyPropset_WriteOnlyPropget_ReadWritePropset_ReadWriteProp.ctorReadOnlyPropWriteOnlyPropReadWritePropM01DFoo`1valuep1p2aryParamArrayAttributep3System.Runtime.InteropServicesOutAttributeSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeCSClasses01ConsoleWriteToStringBase_TT Base_TParamsT Base_ParamsT BaseNV_VV Base_VObj Base_VParams zJC6z\V4      (           TWrapNonExceptionThrows'' '_CorDllMainmscoree.dll% @0HX@TT4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0@InternalNameCSClasses01.dll(LegalCopyright HOriginalFilenameCSClasses01.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 7
MZ@ !L!This program cannot be run in DOS mode. $PELxN! ' @@ @'W@`  H.text  `.rsrc@ @@.reloc `@B'HT!@0 { +*&}*0 { +*&}*( *6rp( *6rp( *6r1p( *0rMp( o +*0rcp( o +*0ryp( o +*( *BSJB v4.0.30319l#~ #Strings#US#GUID#BlobW %3   LE b& n& & E? lLLE&/&s P xh t    " * 3: J R !YJ! )19fA Ip x..# a a ak|u<Sjl<Module>CSClasses01.dllICSPropImplMetadataICSGenImpl`2mscorlibSystemObjectCSInterfaces01ICSPropTVEFooefooget_ReadOnlyPropset_WriteOnlyPropget_ReadWritePropset_ReadWriteProp.ctorReadOnlyPropWriteOnlyPropReadWritePropM01DFoo`1valuep1p2aryParamArrayAttributep3System.Runtime.InteropServicesOutAttributeSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeCSClasses01ConsoleWriteToStringBase_TT Base_TParamsT Base_ParamsT BaseNV_VV Base_VObj Base_VParams zJC6z\V4      (           TWrapNonExceptionThrows'' '_CorDllMainmscoree.dll% @0HX@TT4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0@InternalNameCSClasses01.dll(LegalCopyright HOriginalFilenameCSClasses01.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 7
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/Shared/Utilities/BloomFilter.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; using System.Collections.Generic; using System.Diagnostics; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal partial class BloomFilter { // From MurmurHash: // 'm' and 'r' are mixing constants generated off-line. // The values for m and r are chosen through experimentation and // supported by evidence that they work well. private const uint Compute_Hash_m = 0x5bd1e995; private const int Compute_Hash_r = 24; private readonly BitArray _bitArray; private readonly int _hashFunctionCount; private readonly bool _isCaseSensitive; /// <summary><![CDATA[ /// 1) n = Number of items in the filter /// /// 2) p = Probability of false positives, (a double between 0 and 1). /// /// 3) m = Number of bits in the filter /// /// 4) k = Number of hash functions /// /// m = ceil((n * log(p)) / log(1.0 / (pow(2.0, log(2.0))))) /// /// k = round(log(2.0) * m / n) /// ]]></summary> public BloomFilter(int expectedCount, double falsePositiveProbability, bool isCaseSensitive) { var m = Math.Max(1, ComputeM(expectedCount, falsePositiveProbability)); var k = Math.Max(1, ComputeK(expectedCount, falsePositiveProbability)); // We must have size in even bytes, so that when we deserialize from bytes we get a bit array with the same count. // The count is used by the hash functions. var sizeInEvenBytes = (m + 7) & ~7; _bitArray = new BitArray(length: sizeInEvenBytes); _hashFunctionCount = k; _isCaseSensitive = isCaseSensitive; } public BloomFilter(double falsePositiveProbability, bool isCaseSensitive, ICollection<string> values) : this(values.Count, falsePositiveProbability, isCaseSensitive) { AddRange(values); } public BloomFilter( double falsePositiveProbability, ICollection<string> stringValues, ICollection<long> longValues) : this(stringValues.Count + longValues.Count, falsePositiveProbability, isCaseSensitive: false) { AddRange(stringValues); AddRange(longValues); } private BloomFilter(BitArray bitArray, int hashFunctionCount, bool isCaseSensitive) { _bitArray = bitArray ?? throw new ArgumentNullException(nameof(bitArray)); _hashFunctionCount = hashFunctionCount; _isCaseSensitive = isCaseSensitive; } // m = ceil((n * log(p)) / log(1.0 / (pow(2.0, log(2.0))))) private static int ComputeM(int expectedCount, double falsePositiveProbability) { var p = falsePositiveProbability; double n = expectedCount; var numerator = n * Math.Log(p); var denominator = Math.Log(1.0 / Math.Pow(2.0, Math.Log(2.0))); return unchecked((int)Math.Ceiling(numerator / denominator)); } // k = round(log(2.0) * m / n) private static int ComputeK(int expectedCount, double falsePositiveProbability) { double n = expectedCount; double m = ComputeM(expectedCount, falsePositiveProbability); var temp = Math.Log(2.0) * m / n; return unchecked((int)Math.Round(temp)); } /// <summary> /// Modification of the murmurhash2 algorithm. Code is simpler because it operates over /// strings instead of byte arrays. Because each string character is two bytes, it is known /// that the input will be an even number of bytes (though not necessarily a multiple of 4). /// /// This is needed over the normal 'string.GetHashCode()' because we need to be able to generate /// 'k' different well distributed hashes for any given string s. Also, we want to be able to /// generate these hashes without allocating any memory. My ideal solution would be to use an /// MD5 hash. However, there appears to be no way to do MD5 in .NET where you can: /// /// a) feed it individual values instead of a byte[] /// /// b) have the hash computed into a byte[] you provide instead of a newly allocated one /// /// Generating 'k' pieces of garbage on each insert and lookup seems very wasteful. So, /// instead, we use murmur hash since it provides well distributed values, allows for a /// seed, and allocates no memory. /// /// Murmur hash is public domain. Actual code is included below as reference. /// </summary> private int ComputeHash(string key, int seed) { unchecked { // Initialize the hash to a 'random' value var numberOfCharsLeft = key.Length; var h = (uint)(seed ^ numberOfCharsLeft); // Mix 4 bytes at a time into the hash. NOTE: 4 bytes is two chars, so we iterate // through the string two chars at a time. var index = 0; while (numberOfCharsLeft >= 2) { var c1 = GetCharacter(key, index); var c2 = GetCharacter(key, index + 1); h = CombineTwoCharacters(h, c1, c2); index += 2; numberOfCharsLeft -= 2; } // Handle the last char (or 2 bytes) if they exist. This happens if the original string had // odd length. if (numberOfCharsLeft == 1) { var c = GetCharacter(key, index); h = CombineLastCharacter(h, c); } // Do a few final mixes of the hash to ensure the last few bytes are well-incorporated. h = FinalMix(h); return (int)h; } } private static int ComputeHash(long key, int seed) { // This is a duplicate of ComputeHash(string key, int seed). However, because // we only have 64bits to encode we just unroll that function here. See // Other function for documentation on what's going on here. unchecked { // Initialize the hash to a 'random' value var numberOfCharsLeft = 4; var h = (uint)(seed ^ numberOfCharsLeft); // Mix 4 bytes at a time into the hash. NOTE: 4 bytes is two chars, so we iterate // through the long two chars at a time. var index = 0; while (numberOfCharsLeft >= 2) { var c1 = GetCharacter(key, index); var c2 = GetCharacter(key, index + 1); h = CombineTwoCharacters(h, c1, c2); index += 2; numberOfCharsLeft -= 2; } Debug.Assert(numberOfCharsLeft == 0); // Do a few final mixes of the hash to ensure the last few bytes are well-incorporated. h = FinalMix(h); return (int)h; } } private static uint CombineLastCharacter(uint h, uint c) { unchecked { h ^= c; h *= Compute_Hash_m; return h; } } private static uint FinalMix(uint h) { unchecked { h ^= h >> 13; h *= Compute_Hash_m; h ^= h >> 15; return h; } } private static uint CombineTwoCharacters(uint h, uint c1, uint c2) { unchecked { var k = c1 | (c2 << 16); k *= Compute_Hash_m; k ^= k >> Compute_Hash_r; k *= Compute_Hash_m; h *= Compute_Hash_m; h ^= k; return h; } } private char GetCharacter(string key, int index) { var c = key[index]; return _isCaseSensitive ? c : char.ToLowerInvariant(c); } private static char GetCharacter(long key, int index) { Debug.Assert(index <= 3); return (char)(key >> (16 * index)); } #if false //----------------------------------------------------------------------------- // MurmurHash2, by Austin Appleby // // Note - This code makes a few assumptions about how your machine behaves - // 1. We can read a 4-byte value from any address without crashing // 2. sizeof(int) == 4 // // And it has a few limitations - // 1. It will not work incrementally. // 2. It will not produce the same results on little-endian and big-endian // machines. unsigned int MurmurHash2(const void* key, int len, unsigned int seed) { // 'm' and 'r' are mixing constants generated offline. // The values for m and r are chosen through experimentation and // supported by evidence that they work well. const unsigned int m = 0x5bd1e995; const int r = 24; // Initialize the hash to a 'random' value unsigned int h = seed ^ len; // Mix 4 bytes at a time into the hash const unsigned char* data = (const unsigned char*)key; while(len >= 4) { unsigned int k = *(unsigned int*)data; k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; data += 4; len -= 4; } // Handle the last few bytes of the input array switch(len) { case 3: h ^= data[2] << 16; case 2: h ^= data[1] << 8; case 1: h ^= data[0]; h *= m; }; // Do a few final mixes of the hash to ensure the last few // bytes are well-incorporated. h ^= h >> 13; h *= m; h ^= h >> 15; return h; } #endif public void AddRange(IEnumerable<string> values) { foreach (var v in values) { Add(v); } } public void AddRange(IEnumerable<long> values) { foreach (var v in values) { Add(v); } } public void Add(string value) { for (var i = 0; i < _hashFunctionCount; i++) { _bitArray[GetBitArrayIndex(value, i)] = true; } } private int GetBitArrayIndex(string value, int i) { var hash = ComputeHash(value, i); hash %= _bitArray.Length; return Math.Abs(hash); } public void Add(long value) { for (var i = 0; i < _hashFunctionCount; i++) { _bitArray[GetBitArrayIndex(value, i)] = true; } } private int GetBitArrayIndex(long value, int i) { var hash = ComputeHash(value, i); hash %= _bitArray.Length; return Math.Abs(hash); } public bool ProbablyContains(string value) { for (var i = 0; i < _hashFunctionCount; i++) { if (!_bitArray[GetBitArrayIndex(value, i)]) { return false; } } return true; } public bool ProbablyContains(long value) { for (var i = 0; i < _hashFunctionCount; i++) { if (!_bitArray[GetBitArrayIndex(value, i)]) { return false; } } return true; } public bool IsEquivalent(BloomFilter filter) { return IsEquivalent(_bitArray, filter._bitArray) && _hashFunctionCount == filter._hashFunctionCount && _isCaseSensitive == filter._isCaseSensitive; } private static bool IsEquivalent(BitArray array1, BitArray array2) { if (array1.Length != array2.Length) { return false; } for (var i = 0; i < array1.Length; i++) { if (array1[i] != array2[i]) { return false; } } return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal partial class BloomFilter { // From MurmurHash: // 'm' and 'r' are mixing constants generated off-line. // The values for m and r are chosen through experimentation and // supported by evidence that they work well. private const uint Compute_Hash_m = 0x5bd1e995; private const int Compute_Hash_r = 24; private readonly BitArray _bitArray; private readonly int _hashFunctionCount; private readonly bool _isCaseSensitive; /// <summary><![CDATA[ /// 1) n = Number of items in the filter /// /// 2) p = Probability of false positives, (a double between 0 and 1). /// /// 3) m = Number of bits in the filter /// /// 4) k = Number of hash functions /// /// m = ceil((n * log(p)) / log(1.0 / (pow(2.0, log(2.0))))) /// /// k = round(log(2.0) * m / n) /// ]]></summary> public BloomFilter(int expectedCount, double falsePositiveProbability, bool isCaseSensitive) { var m = Math.Max(1, ComputeM(expectedCount, falsePositiveProbability)); var k = Math.Max(1, ComputeK(expectedCount, falsePositiveProbability)); // We must have size in even bytes, so that when we deserialize from bytes we get a bit array with the same count. // The count is used by the hash functions. var sizeInEvenBytes = (m + 7) & ~7; _bitArray = new BitArray(length: sizeInEvenBytes); _hashFunctionCount = k; _isCaseSensitive = isCaseSensitive; } public BloomFilter(double falsePositiveProbability, bool isCaseSensitive, ICollection<string> values) : this(values.Count, falsePositiveProbability, isCaseSensitive) { AddRange(values); } public BloomFilter( double falsePositiveProbability, ICollection<string> stringValues, ICollection<long> longValues) : this(stringValues.Count + longValues.Count, falsePositiveProbability, isCaseSensitive: false) { AddRange(stringValues); AddRange(longValues); } private BloomFilter(BitArray bitArray, int hashFunctionCount, bool isCaseSensitive) { _bitArray = bitArray ?? throw new ArgumentNullException(nameof(bitArray)); _hashFunctionCount = hashFunctionCount; _isCaseSensitive = isCaseSensitive; } // m = ceil((n * log(p)) / log(1.0 / (pow(2.0, log(2.0))))) private static int ComputeM(int expectedCount, double falsePositiveProbability) { var p = falsePositiveProbability; double n = expectedCount; var numerator = n * Math.Log(p); var denominator = Math.Log(1.0 / Math.Pow(2.0, Math.Log(2.0))); return unchecked((int)Math.Ceiling(numerator / denominator)); } // k = round(log(2.0) * m / n) private static int ComputeK(int expectedCount, double falsePositiveProbability) { double n = expectedCount; double m = ComputeM(expectedCount, falsePositiveProbability); var temp = Math.Log(2.0) * m / n; return unchecked((int)Math.Round(temp)); } /// <summary> /// Modification of the murmurhash2 algorithm. Code is simpler because it operates over /// strings instead of byte arrays. Because each string character is two bytes, it is known /// that the input will be an even number of bytes (though not necessarily a multiple of 4). /// /// This is needed over the normal 'string.GetHashCode()' because we need to be able to generate /// 'k' different well distributed hashes for any given string s. Also, we want to be able to /// generate these hashes without allocating any memory. My ideal solution would be to use an /// MD5 hash. However, there appears to be no way to do MD5 in .NET where you can: /// /// a) feed it individual values instead of a byte[] /// /// b) have the hash computed into a byte[] you provide instead of a newly allocated one /// /// Generating 'k' pieces of garbage on each insert and lookup seems very wasteful. So, /// instead, we use murmur hash since it provides well distributed values, allows for a /// seed, and allocates no memory. /// /// Murmur hash is public domain. Actual code is included below as reference. /// </summary> private int ComputeHash(string key, int seed) { unchecked { // Initialize the hash to a 'random' value var numberOfCharsLeft = key.Length; var h = (uint)(seed ^ numberOfCharsLeft); // Mix 4 bytes at a time into the hash. NOTE: 4 bytes is two chars, so we iterate // through the string two chars at a time. var index = 0; while (numberOfCharsLeft >= 2) { var c1 = GetCharacter(key, index); var c2 = GetCharacter(key, index + 1); h = CombineTwoCharacters(h, c1, c2); index += 2; numberOfCharsLeft -= 2; } // Handle the last char (or 2 bytes) if they exist. This happens if the original string had // odd length. if (numberOfCharsLeft == 1) { var c = GetCharacter(key, index); h = CombineLastCharacter(h, c); } // Do a few final mixes of the hash to ensure the last few bytes are well-incorporated. h = FinalMix(h); return (int)h; } } private static int ComputeHash(long key, int seed) { // This is a duplicate of ComputeHash(string key, int seed). However, because // we only have 64bits to encode we just unroll that function here. See // Other function for documentation on what's going on here. unchecked { // Initialize the hash to a 'random' value var numberOfCharsLeft = 4; var h = (uint)(seed ^ numberOfCharsLeft); // Mix 4 bytes at a time into the hash. NOTE: 4 bytes is two chars, so we iterate // through the long two chars at a time. var index = 0; while (numberOfCharsLeft >= 2) { var c1 = GetCharacter(key, index); var c2 = GetCharacter(key, index + 1); h = CombineTwoCharacters(h, c1, c2); index += 2; numberOfCharsLeft -= 2; } Debug.Assert(numberOfCharsLeft == 0); // Do a few final mixes of the hash to ensure the last few bytes are well-incorporated. h = FinalMix(h); return (int)h; } } private static uint CombineLastCharacter(uint h, uint c) { unchecked { h ^= c; h *= Compute_Hash_m; return h; } } private static uint FinalMix(uint h) { unchecked { h ^= h >> 13; h *= Compute_Hash_m; h ^= h >> 15; return h; } } private static uint CombineTwoCharacters(uint h, uint c1, uint c2) { unchecked { var k = c1 | (c2 << 16); k *= Compute_Hash_m; k ^= k >> Compute_Hash_r; k *= Compute_Hash_m; h *= Compute_Hash_m; h ^= k; return h; } } private char GetCharacter(string key, int index) { var c = key[index]; return _isCaseSensitive ? c : char.ToLowerInvariant(c); } private static char GetCharacter(long key, int index) { Debug.Assert(index <= 3); return (char)(key >> (16 * index)); } #if false //----------------------------------------------------------------------------- // MurmurHash2, by Austin Appleby // // Note - This code makes a few assumptions about how your machine behaves - // 1. We can read a 4-byte value from any address without crashing // 2. sizeof(int) == 4 // // And it has a few limitations - // 1. It will not work incrementally. // 2. It will not produce the same results on little-endian and big-endian // machines. unsigned int MurmurHash2(const void* key, int len, unsigned int seed) { // 'm' and 'r' are mixing constants generated offline. // The values for m and r are chosen through experimentation and // supported by evidence that they work well. const unsigned int m = 0x5bd1e995; const int r = 24; // Initialize the hash to a 'random' value unsigned int h = seed ^ len; // Mix 4 bytes at a time into the hash const unsigned char* data = (const unsigned char*)key; while(len >= 4) { unsigned int k = *(unsigned int*)data; k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; data += 4; len -= 4; } // Handle the last few bytes of the input array switch(len) { case 3: h ^= data[2] << 16; case 2: h ^= data[1] << 8; case 1: h ^= data[0]; h *= m; }; // Do a few final mixes of the hash to ensure the last few // bytes are well-incorporated. h ^= h >> 13; h *= m; h ^= h >> 15; return h; } #endif public void AddRange(IEnumerable<string> values) { foreach (var v in values) { Add(v); } } public void AddRange(IEnumerable<long> values) { foreach (var v in values) { Add(v); } } public void Add(string value) { for (var i = 0; i < _hashFunctionCount; i++) { _bitArray[GetBitArrayIndex(value, i)] = true; } } private int GetBitArrayIndex(string value, int i) { var hash = ComputeHash(value, i); hash %= _bitArray.Length; return Math.Abs(hash); } public void Add(long value) { for (var i = 0; i < _hashFunctionCount; i++) { _bitArray[GetBitArrayIndex(value, i)] = true; } } private int GetBitArrayIndex(long value, int i) { var hash = ComputeHash(value, i); hash %= _bitArray.Length; return Math.Abs(hash); } public bool ProbablyContains(string value) { for (var i = 0; i < _hashFunctionCount; i++) { if (!_bitArray[GetBitArrayIndex(value, i)]) { return false; } } return true; } public bool ProbablyContains(long value) { for (var i = 0; i < _hashFunctionCount; i++) { if (!_bitArray[GetBitArrayIndex(value, i)]) { return false; } } return true; } public bool IsEquivalent(BloomFilter filter) { return IsEquivalent(_bitArray, filter._bitArray) && _hashFunctionCount == filter._hashFunctionCount && _isCaseSensitive == filter._isCaseSensitive; } private static bool IsEquivalent(BitArray array1, BitArray array2) { if (array1.Length != array2.Length) { return false; } for (var i = 0; i < array1.Length; i++) { if (array1[i] != array2[i]) { return false; } } return true; } } }
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Portable/Binding/FinallyBlockBinder.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.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' Binder for Finally blocks. ''' Its purpose is to hide exit try label of the enclosing try binder. ''' </summary> Friend NotInheritable Class FinallyBlockBinder Inherits ExitableStatementBinder Public Sub New(enclosing As Binder) MyBase.New(enclosing, continueKind:=SyntaxKind.None, exitKind:=SyntaxKind.None) End Sub Public Overrides Function GetExitLabel(exitSyntaxKind As SyntaxKind) As LabelSymbol If exitSyntaxKind = SyntaxKind.ExitTryStatement Then ' Skip parent try binder. ' Its exit label is not in scope when in Finally block Return ContainingBinder.ContainingBinder.GetExitLabel(exitSyntaxKind) End If Return MyBase.GetExitLabel(exitSyntaxKind) 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.Collections Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' Binder for Finally blocks. ''' Its purpose is to hide exit try label of the enclosing try binder. ''' </summary> Friend NotInheritable Class FinallyBlockBinder Inherits ExitableStatementBinder Public Sub New(enclosing As Binder) MyBase.New(enclosing, continueKind:=SyntaxKind.None, exitKind:=SyntaxKind.None) End Sub Public Overrides Function GetExitLabel(exitSyntaxKind As SyntaxKind) As LabelSymbol If exitSyntaxKind = SyntaxKind.ExitTryStatement Then ' Skip parent try binder. ' Its exit label is not in scope when in Finally block Return ContainingBinder.ContainingBinder.GetExitLabel(exitSyntaxKind) End If Return MyBase.GetExitLabel(exitSyntaxKind) End Function End Class End Namespace
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./docs/features/wildcards.work.md
work items remaining for wildcards ================================== ### Specs - [ ] Gather together a specification document - [ ] Language behavior (e.g. [this](https://github.com/dotnet/roslyn/issues/14862) and [this](https://github.com/dotnet/roslyn/issues/14794) and [this](https://github.com/dotnet/roslyn/issues/14832)) - [ ] [SemanticModel behavior](https://gist.github.com/gafter/ab10e413efe3a066209cbf14cb874988) (see also [here](https://gist.github.com/gafter/37305d619bd04511f4f66b86f6f2d3a5)) - [ ] Warnings (for expression variables declared but not used) - [x] Debugging (value discarded is not visible in debugger) ### Compiler - [x] Syntax model changes - [x] Symbol changes - [x] Parsing for the short-form wildcard pattern `_` - [x] Implement binding of wildcards - [x] In a pattern - [x] In a deconstruction declaration - [x] In a deconstruction assignment expression - [ ] In an out argument (in every argument context) - [x] Both the long form `var _` and the short form `_` - [x] Type inference for wildcards in each context - [ ] Implement semantic model changes - [ ] `GetTypeInfo` of a wildcard expression `_` should be the type of the discarded value - [ ] `GetSymbolInfo` of a wildcard expression `_` should be an `IDiscardedSymbol` - [x] Implement lowering of wildcards - [x] In a pattern - [x] In a deconstruction declaration - [x] In a deconstruction assignment expression - [ ] In an out argument (in each argument context) ### Testing - [ ] Symbol tests - [ ] Syntax tests - [ ] SemanticModel tests - [ ] Language static semantic tests - [ ] Runtime behavioral tests - [ ] PDB tests - [ ] Scripting tests - [ ] EE tests - [ ] In a pattern context - [ ] In a deconstruction declaration context - [ ] In a deconstruction assignment expression context - [ ] In an out argument (in every argument context) - [ ] Both the long form `var _` and the short form `_`, where permitted - [ ] In the long/short form when there is/not a conflicting name in scope
work items remaining for wildcards ================================== ### Specs - [ ] Gather together a specification document - [ ] Language behavior (e.g. [this](https://github.com/dotnet/roslyn/issues/14862) and [this](https://github.com/dotnet/roslyn/issues/14794) and [this](https://github.com/dotnet/roslyn/issues/14832)) - [ ] [SemanticModel behavior](https://gist.github.com/gafter/ab10e413efe3a066209cbf14cb874988) (see also [here](https://gist.github.com/gafter/37305d619bd04511f4f66b86f6f2d3a5)) - [ ] Warnings (for expression variables declared but not used) - [x] Debugging (value discarded is not visible in debugger) ### Compiler - [x] Syntax model changes - [x] Symbol changes - [x] Parsing for the short-form wildcard pattern `_` - [x] Implement binding of wildcards - [x] In a pattern - [x] In a deconstruction declaration - [x] In a deconstruction assignment expression - [ ] In an out argument (in every argument context) - [x] Both the long form `var _` and the short form `_` - [x] Type inference for wildcards in each context - [ ] Implement semantic model changes - [ ] `GetTypeInfo` of a wildcard expression `_` should be the type of the discarded value - [ ] `GetSymbolInfo` of a wildcard expression `_` should be an `IDiscardedSymbol` - [x] Implement lowering of wildcards - [x] In a pattern - [x] In a deconstruction declaration - [x] In a deconstruction assignment expression - [ ] In an out argument (in each argument context) ### Testing - [ ] Symbol tests - [ ] Syntax tests - [ ] SemanticModel tests - [ ] Language static semantic tests - [ ] Runtime behavioral tests - [ ] PDB tests - [ ] Scripting tests - [ ] EE tests - [ ] In a pattern context - [ ] In a deconstruction declaration context - [ ] In a deconstruction assignment expression context - [ ] In an out argument (in every argument context) - [ ] Both the long form `var _` and the short form `_`, where permitted - [ ] In the long/short form when there is/not a conflicting name in scope
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/SyntaxTreeExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static partial class SyntaxTreeExtensions { public static ISet<SyntaxKind> GetPrecedingModifiers( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) => syntaxTree.GetPrecedingModifiers(position, tokenOnLeftOfPosition, out var _); public static ISet<SyntaxKind> GetPrecedingModifiers( #pragma warning disable IDE0060 // Remove unused parameter - Unused this parameter for consistency with other extension methods. this SyntaxTree syntaxTree, #pragma warning restore IDE0060 // Remove unused parameter int position, SyntaxToken tokenOnLeftOfPosition, out int positionBeforeModifiers) { var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); var result = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer); while (true) { switch (token.Kind()) { case SyntaxKind.PublicKeyword: case SyntaxKind.InternalKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.PrivateKeyword: case SyntaxKind.SealedKeyword: case SyntaxKind.AbstractKeyword: case SyntaxKind.StaticKeyword: case SyntaxKind.VirtualKeyword: case SyntaxKind.ExternKeyword: case SyntaxKind.NewKeyword: case SyntaxKind.OverrideKeyword: case SyntaxKind.ReadOnlyKeyword: case SyntaxKind.VolatileKeyword: case SyntaxKind.UnsafeKeyword: case SyntaxKind.AsyncKeyword: case SyntaxKind.RefKeyword: case SyntaxKind.OutKeyword: case SyntaxKind.InKeyword: result.Add(token.Kind()); token = token.GetPreviousToken(includeSkipped: true); continue; case SyntaxKind.IdentifierToken: if (token.HasMatchingText(SyntaxKind.AsyncKeyword)) { result.Add(SyntaxKind.AsyncKeyword); token = token.GetPreviousToken(includeSkipped: true); continue; } break; } break; } positionBeforeModifiers = token.FullSpan.End; return result; } public static TypeDeclarationSyntax? GetContainingTypeDeclaration( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { return syntaxTree.GetContainingTypeDeclarations(position, cancellationToken).FirstOrDefault(); } public static BaseTypeDeclarationSyntax? GetContainingTypeOrEnumDeclaration( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { return syntaxTree.GetContainingTypeOrEnumDeclarations(position, cancellationToken).FirstOrDefault(); } public static IEnumerable<TypeDeclarationSyntax> GetContainingTypeDeclarations( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); return token.GetAncestors<TypeDeclarationSyntax>().Where(t => { return BaseTypeDeclarationContainsPosition(t, position); }); } private static bool BaseTypeDeclarationContainsPosition(BaseTypeDeclarationSyntax declaration, int position) { if (position <= declaration.OpenBraceToken.SpanStart) { return false; } if (declaration.CloseBraceToken.IsMissing) { return true; } return position <= declaration.CloseBraceToken.SpanStart; } public static IEnumerable<BaseTypeDeclarationSyntax> GetContainingTypeOrEnumDeclarations( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); return token.GetAncestors<BaseTypeDeclarationSyntax>().Where(t => BaseTypeDeclarationContainsPosition(t, position)); } private static readonly Func<SyntaxKind, bool> s_isDotOrArrow = k => k == SyntaxKind.DotToken || k == SyntaxKind.MinusGreaterThanToken; private static readonly Func<SyntaxKind, bool> s_isDotOrArrowOrColonColon = k => k == SyntaxKind.DotToken || k == SyntaxKind.MinusGreaterThanToken || k == SyntaxKind.ColonColonToken; public static bool IsRightOfDotOrArrowOrColonColon(this SyntaxTree syntaxTree, int position, SyntaxToken targetToken, CancellationToken cancellationToken) { return (targetToken.IsKind(SyntaxKind.DotDotToken) && position == targetToken.SpanStart + 1) || syntaxTree.IsRightOf(position, s_isDotOrArrowOrColonColon, cancellationToken); } public static bool IsRightOfDotOrArrow(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) => syntaxTree.IsRightOf(position, s_isDotOrArrow, cancellationToken); private static bool IsRightOf( this SyntaxTree syntaxTree, int position, Func<SyntaxKind, bool> predicate, CancellationToken cancellationToken) { var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); if (token.Kind() == SyntaxKind.None) { return false; } return predicate(token.Kind()); } public static bool IsRightOfNumericLiteral(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); return token.Kind() == SyntaxKind.NumericLiteralToken; } public static bool IsAfterKeyword(this SyntaxTree syntaxTree, int position, SyntaxKind kind, CancellationToken cancellationToken) { var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); return token.Kind() == kind; } public static bool IsEntirelyWithinNonUserCodeComment(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var inNonUserSingleLineDocComment = syntaxTree.IsEntirelyWithinSingleLineDocComment(position, cancellationToken) && !syntaxTree.IsEntirelyWithinCrefSyntax(position, cancellationToken); return syntaxTree.IsEntirelyWithinTopLevelSingleLineComment(position, cancellationToken) || syntaxTree.IsEntirelyWithinPreProcessorSingleLineComment(position, cancellationToken) || syntaxTree.IsEntirelyWithinMultiLineComment(position, cancellationToken) || syntaxTree.IsEntirelyWithinMultiLineDocComment(position, cancellationToken) || inNonUserSingleLineDocComment; } public static bool IsEntirelyWithinComment(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { return syntaxTree.IsEntirelyWithinTopLevelSingleLineComment(position, cancellationToken) || syntaxTree.IsEntirelyWithinPreProcessorSingleLineComment(position, cancellationToken) || syntaxTree.IsEntirelyWithinMultiLineComment(position, cancellationToken) || syntaxTree.IsEntirelyWithinMultiLineDocComment(position, cancellationToken) || syntaxTree.IsEntirelyWithinSingleLineDocComment(position, cancellationToken); } public static bool IsCrefContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDocumentationComments: true); token = token.GetPreviousTokenIfTouchingWord(position); if (token.Parent is XmlCrefAttributeSyntax attribute) { return token == attribute.StartQuoteToken; } return false; } public static bool IsEntirelyWithinCrefSyntax(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { if (syntaxTree.IsCrefContext(position, cancellationToken)) { return true; } var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDocumentationComments: true); return token.GetAncestor<CrefSyntax>() != null; } public static bool IsEntirelyWithinSingleLineDocComment( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var root = (CompilationUnitSyntax)syntaxTree.GetRoot(cancellationToken); var trivia = root.FindTrivia(position); // If we ask right at the end of the file, we'll get back nothing. // So move back in that case and ask again. var eofPosition = root.FullWidth(); if (position == eofPosition) { var eof = root.EndOfFileToken; if (eof.HasLeadingTrivia) { trivia = eof.LeadingTrivia.Last(); } } if (trivia.IsSingleLineDocComment()) { RoslynDebug.Assert(trivia.HasStructure); var fullSpan = trivia.FullSpan; var endsWithNewLine = trivia.GetStructure()!.GetLastToken(includeSkipped: true).Kind() == SyntaxKind.XmlTextLiteralNewLineToken; if (endsWithNewLine) { if (position > fullSpan.Start && position < fullSpan.End) { return true; } } else { if (position > fullSpan.Start && position <= fullSpan.End) { return true; } } } return false; } public static bool IsEntirelyWithinMultiLineDocComment( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position); if (trivia.IsMultiLineDocComment()) { var span = trivia.FullSpan; if (position > span.Start && position < span.End) { return true; } } return false; } public static bool IsEntirelyWithinMultiLineComment( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var trivia = syntaxTree.FindTriviaAndAdjustForEndOfFile(position, cancellationToken); if (trivia.IsMultiLineComment()) { var span = trivia.FullSpan; return trivia.IsCompleteMultiLineComment() ? position > span.Start && position < span.End : position > span.Start && position <= span.End; } return false; } public static bool IsEntirelyWithinConflictMarker( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var trivia = syntaxTree.FindTriviaAndAdjustForEndOfFile(position, cancellationToken); if (trivia.Kind() == SyntaxKind.EndOfLineTrivia) { // Check if we're on the newline right at the end of a comment trivia = trivia.GetPreviousTrivia(syntaxTree, cancellationToken); } return trivia.Kind() == SyntaxKind.ConflictMarkerTrivia; } public static bool IsEntirelyWithinTopLevelSingleLineComment( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var trivia = syntaxTree.FindTriviaAndAdjustForEndOfFile(position, cancellationToken); if (trivia.Kind() == SyntaxKind.EndOfLineTrivia) { // Check if we're on the newline right at the end of a comment trivia = trivia.GetPreviousTrivia(syntaxTree, cancellationToken); } if (trivia.IsSingleLineComment() || trivia.IsShebangDirective()) { var span = trivia.FullSpan; if (position > span.Start && position <= span.End) { return true; } } return false; } public static bool IsEntirelyWithinPreProcessorSingleLineComment( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { // Search inside trivia for directives to ensure that we recognize // single-line comments at the end of preprocessor directives. var trivia = syntaxTree.FindTriviaAndAdjustForEndOfFile(position, cancellationToken, findInsideTrivia: true); if (trivia.Kind() == SyntaxKind.EndOfLineTrivia) { // Check if we're on the newline right at the end of a comment trivia = trivia.GetPreviousTrivia(syntaxTree, cancellationToken, findInsideTrivia: true); } if (trivia.IsSingleLineComment()) { var span = trivia.FullSpan; if (position > span.Start && position <= span.End) { return true; } } return false; } private static bool AtEndOfIncompleteStringOrCharLiteral(SyntaxToken token, int position, char lastChar) { if (!token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.CharacterLiteralToken)) { throw new ArgumentException(CSharpCompilerExtensionsResources.Expected_string_or_char_literal, nameof(token)); } var startLength = 1; if (token.IsVerbatimStringLiteral()) { startLength = 2; } return position == token.Span.End && (token.Span.Length == startLength || (token.Span.Length > startLength && token.ToString().Cast<char>().LastOrDefault() != lastChar)); } public static bool IsEntirelyWithinStringOrCharLiteral( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { return syntaxTree.IsEntirelyWithinStringLiteral(position, cancellationToken) || syntaxTree.IsEntirelyWithinCharLiteral(position, cancellationToken); } public static bool IsEntirelyWithinStringLiteral( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var token = syntaxTree.GetRoot(cancellationToken).FindToken(position, findInsideTrivia: true); // If we ask right at the end of the file, we'll get back nothing. We handle that case // specially for now, though SyntaxTree.FindToken should work at the end of a file. if (token.IsKind(SyntaxKind.EndOfDirectiveToken, SyntaxKind.EndOfFileToken)) { token = token.GetPreviousToken(includeSkipped: true, includeDirectives: true); } if (token.IsKind(SyntaxKind.StringLiteralToken)) { var span = token.Span; // cases: // "|" // "| (e.g. incomplete string literal) return (position > span.Start && position < span.End) || AtEndOfIncompleteStringOrCharLiteral(token, position, '"'); } if (token.IsKind(SyntaxKind.InterpolatedStringStartToken, SyntaxKind.InterpolatedStringTextToken, SyntaxKind.InterpolatedStringEndToken)) { return token.SpanStart < position && token.Span.End > position; } return false; } public static bool IsEntirelyWithinCharLiteral( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var root = (CompilationUnitSyntax)syntaxTree.GetRoot(cancellationToken); var token = root.FindToken(position, findInsideTrivia: true); // If we ask right at the end of the file, we'll get back nothing. // We handle that case specially for now, though SyntaxTree.FindToken should // work at the end of a file. if (position == root.FullWidth()) { token = root.EndOfFileToken.GetPreviousToken(includeSkipped: true, includeDirectives: true); } if (token.Kind() == SyntaxKind.CharacterLiteralToken) { var span = token.Span; // cases: // '|' // '| (e.g. incomplete char literal) return (position > span.Start && position < span.End) || AtEndOfIncompleteStringOrCharLiteral(token, position, '\''); } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static partial class SyntaxTreeExtensions { public static ISet<SyntaxKind> GetPrecedingModifiers( this SyntaxTree syntaxTree, int position, SyntaxToken tokenOnLeftOfPosition) => syntaxTree.GetPrecedingModifiers(position, tokenOnLeftOfPosition, out var _); public static ISet<SyntaxKind> GetPrecedingModifiers( #pragma warning disable IDE0060 // Remove unused parameter - Unused this parameter for consistency with other extension methods. this SyntaxTree syntaxTree, #pragma warning restore IDE0060 // Remove unused parameter int position, SyntaxToken tokenOnLeftOfPosition, out int positionBeforeModifiers) { var token = tokenOnLeftOfPosition; token = token.GetPreviousTokenIfTouchingWord(position); var result = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer); while (true) { switch (token.Kind()) { case SyntaxKind.PublicKeyword: case SyntaxKind.InternalKeyword: case SyntaxKind.ProtectedKeyword: case SyntaxKind.PrivateKeyword: case SyntaxKind.SealedKeyword: case SyntaxKind.AbstractKeyword: case SyntaxKind.StaticKeyword: case SyntaxKind.VirtualKeyword: case SyntaxKind.ExternKeyword: case SyntaxKind.NewKeyword: case SyntaxKind.OverrideKeyword: case SyntaxKind.ReadOnlyKeyword: case SyntaxKind.VolatileKeyword: case SyntaxKind.UnsafeKeyword: case SyntaxKind.AsyncKeyword: case SyntaxKind.RefKeyword: case SyntaxKind.OutKeyword: case SyntaxKind.InKeyword: result.Add(token.Kind()); token = token.GetPreviousToken(includeSkipped: true); continue; case SyntaxKind.IdentifierToken: if (token.HasMatchingText(SyntaxKind.AsyncKeyword)) { result.Add(SyntaxKind.AsyncKeyword); token = token.GetPreviousToken(includeSkipped: true); continue; } break; } break; } positionBeforeModifiers = token.FullSpan.End; return result; } public static TypeDeclarationSyntax? GetContainingTypeDeclaration( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { return syntaxTree.GetContainingTypeDeclarations(position, cancellationToken).FirstOrDefault(); } public static BaseTypeDeclarationSyntax? GetContainingTypeOrEnumDeclaration( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { return syntaxTree.GetContainingTypeOrEnumDeclarations(position, cancellationToken).FirstOrDefault(); } public static IEnumerable<TypeDeclarationSyntax> GetContainingTypeDeclarations( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); return token.GetAncestors<TypeDeclarationSyntax>().Where(t => { return BaseTypeDeclarationContainsPosition(t, position); }); } private static bool BaseTypeDeclarationContainsPosition(BaseTypeDeclarationSyntax declaration, int position) { if (position <= declaration.OpenBraceToken.SpanStart) { return false; } if (declaration.CloseBraceToken.IsMissing) { return true; } return position <= declaration.CloseBraceToken.SpanStart; } public static IEnumerable<BaseTypeDeclarationSyntax> GetContainingTypeOrEnumDeclarations( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); return token.GetAncestors<BaseTypeDeclarationSyntax>().Where(t => BaseTypeDeclarationContainsPosition(t, position)); } private static readonly Func<SyntaxKind, bool> s_isDotOrArrow = k => k == SyntaxKind.DotToken || k == SyntaxKind.MinusGreaterThanToken; private static readonly Func<SyntaxKind, bool> s_isDotOrArrowOrColonColon = k => k == SyntaxKind.DotToken || k == SyntaxKind.MinusGreaterThanToken || k == SyntaxKind.ColonColonToken; public static bool IsRightOfDotOrArrowOrColonColon(this SyntaxTree syntaxTree, int position, SyntaxToken targetToken, CancellationToken cancellationToken) { return (targetToken.IsKind(SyntaxKind.DotDotToken) && position == targetToken.SpanStart + 1) || syntaxTree.IsRightOf(position, s_isDotOrArrowOrColonColon, cancellationToken); } public static bool IsRightOfDotOrArrow(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) => syntaxTree.IsRightOf(position, s_isDotOrArrow, cancellationToken); private static bool IsRightOf( this SyntaxTree syntaxTree, int position, Func<SyntaxKind, bool> predicate, CancellationToken cancellationToken) { var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); if (token.Kind() == SyntaxKind.None) { return false; } return predicate(token.Kind()); } public static bool IsRightOfNumericLiteral(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); return token.Kind() == SyntaxKind.NumericLiteralToken; } public static bool IsAfterKeyword(this SyntaxTree syntaxTree, int position, SyntaxKind kind, CancellationToken cancellationToken) { var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); return token.Kind() == kind; } public static bool IsEntirelyWithinNonUserCodeComment(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var inNonUserSingleLineDocComment = syntaxTree.IsEntirelyWithinSingleLineDocComment(position, cancellationToken) && !syntaxTree.IsEntirelyWithinCrefSyntax(position, cancellationToken); return syntaxTree.IsEntirelyWithinTopLevelSingleLineComment(position, cancellationToken) || syntaxTree.IsEntirelyWithinPreProcessorSingleLineComment(position, cancellationToken) || syntaxTree.IsEntirelyWithinMultiLineComment(position, cancellationToken) || syntaxTree.IsEntirelyWithinMultiLineDocComment(position, cancellationToken) || inNonUserSingleLineDocComment; } public static bool IsEntirelyWithinComment(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { return syntaxTree.IsEntirelyWithinTopLevelSingleLineComment(position, cancellationToken) || syntaxTree.IsEntirelyWithinPreProcessorSingleLineComment(position, cancellationToken) || syntaxTree.IsEntirelyWithinMultiLineComment(position, cancellationToken) || syntaxTree.IsEntirelyWithinMultiLineDocComment(position, cancellationToken) || syntaxTree.IsEntirelyWithinSingleLineDocComment(position, cancellationToken); } public static bool IsCrefContext(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDocumentationComments: true); token = token.GetPreviousTokenIfTouchingWord(position); if (token.Parent is XmlCrefAttributeSyntax attribute) { return token == attribute.StartQuoteToken; } return false; } public static bool IsEntirelyWithinCrefSyntax(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { if (syntaxTree.IsCrefContext(position, cancellationToken)) { return true; } var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDocumentationComments: true); return token.GetAncestor<CrefSyntax>() != null; } public static bool IsEntirelyWithinSingleLineDocComment( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var root = (CompilationUnitSyntax)syntaxTree.GetRoot(cancellationToken); var trivia = root.FindTrivia(position); // If we ask right at the end of the file, we'll get back nothing. // So move back in that case and ask again. var eofPosition = root.FullWidth(); if (position == eofPosition) { var eof = root.EndOfFileToken; if (eof.HasLeadingTrivia) { trivia = eof.LeadingTrivia.Last(); } } if (trivia.IsSingleLineDocComment()) { RoslynDebug.Assert(trivia.HasStructure); var fullSpan = trivia.FullSpan; var endsWithNewLine = trivia.GetStructure()!.GetLastToken(includeSkipped: true).Kind() == SyntaxKind.XmlTextLiteralNewLineToken; if (endsWithNewLine) { if (position > fullSpan.Start && position < fullSpan.End) { return true; } } else { if (position > fullSpan.Start && position <= fullSpan.End) { return true; } } } return false; } public static bool IsEntirelyWithinMultiLineDocComment( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position); if (trivia.IsMultiLineDocComment()) { var span = trivia.FullSpan; if (position > span.Start && position < span.End) { return true; } } return false; } public static bool IsEntirelyWithinMultiLineComment( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var trivia = syntaxTree.FindTriviaAndAdjustForEndOfFile(position, cancellationToken); if (trivia.IsMultiLineComment()) { var span = trivia.FullSpan; return trivia.IsCompleteMultiLineComment() ? position > span.Start && position < span.End : position > span.Start && position <= span.End; } return false; } public static bool IsEntirelyWithinConflictMarker( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var trivia = syntaxTree.FindTriviaAndAdjustForEndOfFile(position, cancellationToken); if (trivia.Kind() == SyntaxKind.EndOfLineTrivia) { // Check if we're on the newline right at the end of a comment trivia = trivia.GetPreviousTrivia(syntaxTree, cancellationToken); } return trivia.Kind() == SyntaxKind.ConflictMarkerTrivia; } public static bool IsEntirelyWithinTopLevelSingleLineComment( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var trivia = syntaxTree.FindTriviaAndAdjustForEndOfFile(position, cancellationToken); if (trivia.Kind() == SyntaxKind.EndOfLineTrivia) { // Check if we're on the newline right at the end of a comment trivia = trivia.GetPreviousTrivia(syntaxTree, cancellationToken); } if (trivia.IsSingleLineComment() || trivia.IsShebangDirective()) { var span = trivia.FullSpan; if (position > span.Start && position <= span.End) { return true; } } return false; } public static bool IsEntirelyWithinPreProcessorSingleLineComment( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { // Search inside trivia for directives to ensure that we recognize // single-line comments at the end of preprocessor directives. var trivia = syntaxTree.FindTriviaAndAdjustForEndOfFile(position, cancellationToken, findInsideTrivia: true); if (trivia.Kind() == SyntaxKind.EndOfLineTrivia) { // Check if we're on the newline right at the end of a comment trivia = trivia.GetPreviousTrivia(syntaxTree, cancellationToken, findInsideTrivia: true); } if (trivia.IsSingleLineComment()) { var span = trivia.FullSpan; if (position > span.Start && position <= span.End) { return true; } } return false; } private static bool AtEndOfIncompleteStringOrCharLiteral(SyntaxToken token, int position, char lastChar) { if (!token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.CharacterLiteralToken)) { throw new ArgumentException(CSharpCompilerExtensionsResources.Expected_string_or_char_literal, nameof(token)); } var startLength = 1; if (token.IsVerbatimStringLiteral()) { startLength = 2; } return position == token.Span.End && (token.Span.Length == startLength || (token.Span.Length > startLength && token.ToString().Cast<char>().LastOrDefault() != lastChar)); } public static bool IsEntirelyWithinStringOrCharLiteral( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { return syntaxTree.IsEntirelyWithinStringLiteral(position, cancellationToken) || syntaxTree.IsEntirelyWithinCharLiteral(position, cancellationToken); } public static bool IsEntirelyWithinStringLiteral( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var token = syntaxTree.GetRoot(cancellationToken).FindToken(position, findInsideTrivia: true); // If we ask right at the end of the file, we'll get back nothing. We handle that case // specially for now, though SyntaxTree.FindToken should work at the end of a file. if (token.IsKind(SyntaxKind.EndOfDirectiveToken, SyntaxKind.EndOfFileToken)) { token = token.GetPreviousToken(includeSkipped: true, includeDirectives: true); } if (token.IsKind(SyntaxKind.StringLiteralToken)) { var span = token.Span; // cases: // "|" // "| (e.g. incomplete string literal) return (position > span.Start && position < span.End) || AtEndOfIncompleteStringOrCharLiteral(token, position, '"'); } if (token.IsKind(SyntaxKind.InterpolatedStringStartToken, SyntaxKind.InterpolatedStringTextToken, SyntaxKind.InterpolatedStringEndToken)) { return token.SpanStart < position && token.Span.End > position; } return false; } public static bool IsEntirelyWithinCharLiteral( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var root = (CompilationUnitSyntax)syntaxTree.GetRoot(cancellationToken); var token = root.FindToken(position, findInsideTrivia: true); // If we ask right at the end of the file, we'll get back nothing. // We handle that case specially for now, though SyntaxTree.FindToken should // work at the end of a file. if (position == root.FullWidth()) { token = root.EndOfFileToken.GetPreviousToken(includeSkipped: true, includeDirectives: true); } if (token.Kind() == SyntaxKind.CharacterLiteralToken) { var span = token.Span; // cases: // '|' // '| (e.g. incomplete char literal) return (position > span.Start && position < span.End) || AtEndOfIncompleteStringOrCharLiteral(token, position, '\''); } return false; } } }
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberFieldSymbol.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.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal abstract class SourceMemberFieldSymbol : SourceFieldSymbolWithSyntaxReference { private readonly DeclarationModifiers _modifiers; internal SourceMemberFieldSymbol( SourceMemberContainerTypeSymbol containingType, DeclarationModifiers modifiers, string name, SyntaxReference syntax, Location location) : base(containingType, name, syntax, location) { _modifiers = modifiers; } protected sealed override DeclarationModifiers Modifiers { get { return _modifiers; } } protected abstract TypeSyntax TypeSyntax { get; } protected abstract SyntaxTokenList ModifiersTokenList { get; } protected void TypeChecks(TypeSymbol type, BindingDiagnosticBag diagnostics) { if (type.IsStatic) { // Cannot declare a variable of static type '{0}' diagnostics.Add(ErrorCode.ERR_VarDeclIsStaticClass, this.ErrorLocation, type); } else if (type.IsVoidType()) { diagnostics.Add(ErrorCode.ERR_FieldCantHaveVoidType, TypeSyntax?.Location ?? this.Locations[0]); } else if (type.IsRestrictedType(ignoreSpanLikeTypes: true)) { diagnostics.Add(ErrorCode.ERR_FieldCantBeRefAny, TypeSyntax?.Location ?? this.Locations[0], type); } else if (type.IsRefLikeType && (this.IsStatic || !containingType.IsRefLikeType)) { diagnostics.Add(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, TypeSyntax?.Location ?? this.Locations[0], type); } else if (IsConst && !type.CanBeConst()) { SyntaxToken constToken = default(SyntaxToken); foreach (var modifier in ModifiersTokenList) { if (modifier.Kind() == SyntaxKind.ConstKeyword) { constToken = modifier; break; } } Debug.Assert(constToken.Kind() == SyntaxKind.ConstKeyword); diagnostics.Add(ErrorCode.ERR_BadConstType, constToken.GetLocation(), type); } else if (IsVolatile && !type.IsValidVolatileFieldType()) { // '{0}': a volatile field cannot be of the type '{1}' diagnostics.Add(ErrorCode.ERR_VolatileStruct, this.ErrorLocation, this, type); } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly); if (!this.IsNoMoreVisibleThan(type, ref useSiteInfo)) { // Inconsistent accessibility: field type '{1}' is less accessible than field '{0}' diagnostics.Add(ErrorCode.ERR_BadVisFieldType, this.ErrorLocation, this, type); } diagnostics.Add(this.ErrorLocation, useSiteInfo); } public abstract bool HasInitializer { get; } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); var compilation = this.DeclaringCompilation; var value = this.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false); // Synthesize DecimalConstantAttribute when the default value is of type decimal if (this.IsConst && value != null && this.Type.SpecialType == SpecialType.System_Decimal) { var data = GetDecodedWellKnownAttributeData(); if (data == null || data.ConstValue == CodeAnalysis.ConstantValue.Unset) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDecimalConstantAttribute(value.DecimalValue)); } } } public override Symbol AssociatedSymbol { get { return null; } } public override int FixedSize { get { Debug.Assert(!this.IsFixedSizeBuffer, "Subclasses representing fixed fields must override"); state.NotePartComplete(CompletionPart.FixedSize); return 0; } } internal static DeclarationModifiers MakeModifiers(NamedTypeSymbol containingType, SyntaxToken firstIdentifier, SyntaxTokenList modifiers, BindingDiagnosticBag diagnostics, out bool modifierErrors) { DeclarationModifiers defaultAccess = (containingType.IsInterface) ? DeclarationModifiers.Public : DeclarationModifiers.Private; DeclarationModifiers allowedModifiers = DeclarationModifiers.AccessibilityMask | DeclarationModifiers.Const | DeclarationModifiers.New | DeclarationModifiers.ReadOnly | DeclarationModifiers.Static | DeclarationModifiers.Volatile | DeclarationModifiers.Fixed | DeclarationModifiers.Unsafe | DeclarationModifiers.Abstract; // filtered out later var errorLocation = new SourceLocation(firstIdentifier); DeclarationModifiers result = ModifierUtils.MakeAndCheckNontypeMemberModifiers( modifiers, defaultAccess, allowedModifiers, errorLocation, diagnostics, out modifierErrors); if ((result & DeclarationModifiers.Abstract) != 0) { diagnostics.Add(ErrorCode.ERR_AbstractField, errorLocation); result &= ~DeclarationModifiers.Abstract; } if ((result & DeclarationModifiers.Fixed) != 0) { if ((result & DeclarationModifiers.Static) != 0) { // The modifier 'static' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.StaticKeyword)); } if ((result & DeclarationModifiers.ReadOnly) != 0) { // The modifier 'readonly' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.ReadOnlyKeyword)); } if ((result & DeclarationModifiers.Const) != 0) { // The modifier 'const' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.ConstKeyword)); } if ((result & DeclarationModifiers.Volatile) != 0) { // The modifier 'volatile' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.VolatileKeyword)); } result &= ~(DeclarationModifiers.Static | DeclarationModifiers.ReadOnly | DeclarationModifiers.Const | DeclarationModifiers.Volatile); Debug.Assert((result & ~(DeclarationModifiers.AccessibilityMask | DeclarationModifiers.Fixed | DeclarationModifiers.Unsafe | DeclarationModifiers.New)) == 0); } if ((result & DeclarationModifiers.Const) != 0) { if ((result & DeclarationModifiers.Static) != 0) { // The constant '{0}' cannot be marked static diagnostics.Add(ErrorCode.ERR_StaticConstant, errorLocation, firstIdentifier.ValueText); } if ((result & DeclarationModifiers.ReadOnly) != 0) { // The modifier 'readonly' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.ReadOnlyKeyword)); } if ((result & DeclarationModifiers.Volatile) != 0) { // The modifier 'volatile' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.VolatileKeyword)); } if ((result & DeclarationModifiers.Unsafe) != 0) { // The modifier 'unsafe' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.UnsafeKeyword)); } result |= DeclarationModifiers.Static; // "constants are considered static members" } else { // NOTE: always cascading on a const, so suppress. // NOTE: we're being a bit sneaky here - we're using the containingType rather than this symbol // to determine whether or not unsafe is allowed. Since this symbol and the containing type are // in the same compilation, it won't make a difference. We do, however, have to pass the error // location explicitly. containingType.CheckUnsafeModifier(result, errorLocation, diagnostics); } return result; } internal sealed override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { while (true) { cancellationToken.ThrowIfCancellationRequested(); var incompletePart = state.NextIncompletePart; switch (incompletePart) { case CompletionPart.Attributes: GetAttributes(); break; case CompletionPart.Type: GetFieldType(ConsList<FieldSymbol>.Empty); break; case CompletionPart.FixedSize: int discarded = this.FixedSize; break; case CompletionPart.ConstantValue: GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false); break; case CompletionPart.None: return; default: // any other values are completion parts intended for other kinds of symbols state.NotePartComplete(CompletionPart.All & ~CompletionPart.FieldSymbolAll); break; } state.SpinWaitComplete(incompletePart, cancellationToken); } } internal override NamedTypeSymbol FixedImplementationType(PEModuleBuilder emitModule) { Debug.Assert(!this.IsFixedSizeBuffer, "Subclasses representing fixed fields must override"); return null; } } internal class SourceMemberFieldSymbolFromDeclarator : SourceMemberFieldSymbol { private readonly bool _hasInitializer; private TypeWithAnnotations.Boxed _lazyType; // Non-zero if the type of the field has been inferred from the type of its initializer expression // and the errors of binding the initializer have been or are being reported to compilation diagnostics. private int _lazyFieldTypeInferred; internal SourceMemberFieldSymbolFromDeclarator( SourceMemberContainerTypeSymbol containingType, VariableDeclaratorSyntax declarator, DeclarationModifiers modifiers, bool modifierErrors, BindingDiagnosticBag diagnostics) : base(containingType, modifiers, declarator.Identifier.ValueText, declarator.GetReference(), declarator.Identifier.GetLocation()) { _hasInitializer = declarator.Initializer != null; this.CheckAccessibility(diagnostics); if (!modifierErrors) { this.ReportModifiersDiagnostics(diagnostics); } if (containingType.IsInterface) { if (this.IsStatic) { Binder.CheckFeatureAvailability(declarator, MessageID.IDS_DefaultInterfaceImplementation, diagnostics, ErrorLocation); if (!ContainingAssembly.RuntimeSupportsDefaultInterfaceImplementation) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, ErrorLocation); } } else { diagnostics.Add(ErrorCode.ERR_InterfacesCantContainFields, ErrorLocation); } } } protected sealed override TypeSyntax TypeSyntax { get { return GetFieldDeclaration(VariableDeclaratorNode).Declaration.Type; } } protected sealed override SyntaxTokenList ModifiersTokenList { get { return GetFieldDeclaration(VariableDeclaratorNode).Modifiers; } } public sealed override bool HasInitializer { get { return _hasInitializer; } } protected VariableDeclaratorSyntax VariableDeclaratorNode { get { return (VariableDeclaratorSyntax)this.SyntaxNode; } } private static BaseFieldDeclarationSyntax GetFieldDeclaration(CSharpSyntaxNode declarator) { return (BaseFieldDeclarationSyntax)declarator.Parent.Parent; } protected override SyntaxList<AttributeListSyntax> AttributeDeclarationSyntaxList { get { if (this.containingType.AnyMemberHasAttributes) { return GetFieldDeclaration(this.SyntaxNode).AttributeLists; } return default(SyntaxList<AttributeListSyntax>); } } internal override bool HasPointerType { get { if (_lazyType != null) { bool isPointerType = _lazyType.Value.DefaultType.Kind switch { SymbolKind.PointerType => true, SymbolKind.FunctionPointerType => true, _ => false }; Debug.Assert(isPointerType == IsPointerFieldSyntactically()); return isPointerType; } return IsPointerFieldSyntactically(); } } private bool IsPointerFieldSyntactically() { var declaration = GetFieldDeclaration(VariableDeclaratorNode).Declaration; if (declaration.Type.Kind() switch { SyntaxKind.PointerType => true, SyntaxKind.FunctionPointerType => true, _ => false }) { // public int * Blah; // pointer return true; } return IsFixedSizeBuffer; } internal sealed override TypeWithAnnotations GetFieldType(ConsList<FieldSymbol> fieldsBeingBound) { Debug.Assert(fieldsBeingBound != null); if (_lazyType != null) { return _lazyType.Value; } var declarator = VariableDeclaratorNode; var fieldSyntax = GetFieldDeclaration(declarator); var typeSyntax = fieldSyntax.Declaration.Type; var compilation = this.DeclaringCompilation; var diagnostics = BindingDiagnosticBag.GetInstance(); TypeWithAnnotations type; // When we have multiple declarators, we report the type diagnostics on only the first. var diagnosticsForFirstDeclarator = BindingDiagnosticBag.GetInstance(); Symbol associatedPropertyOrEvent = this.AssociatedSymbol; if ((object)associatedPropertyOrEvent != null && associatedPropertyOrEvent.Kind == SymbolKind.Event) { EventSymbol @event = (EventSymbol)associatedPropertyOrEvent; if (@event.IsWindowsRuntimeEvent) { NamedTypeSymbol tokenTableType = this.DeclaringCompilation.GetWellKnownType(WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T); Binder.ReportUseSite(tokenTableType, diagnosticsForFirstDeclarator, this.ErrorLocation); // CONSIDER: Do we want to guard against the possibility that someone has created their own EventRegistrationTokenTable<T> // type that has additional generic constraints? type = TypeWithAnnotations.Create(tokenTableType.Construct(ImmutableArray.Create(@event.TypeWithAnnotations))); } else { type = @event.TypeWithAnnotations; } } else { var binderFactory = compilation.GetBinderFactory(SyntaxTree); var binder = binderFactory.GetBinder(typeSyntax); binder = binder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this); if (!ContainingType.IsScriptClass) { type = binder.BindType(typeSyntax, diagnosticsForFirstDeclarator); } else { bool isVar; type = binder.BindTypeOrVarKeyword(typeSyntax, diagnostics, out isVar); Debug.Assert(type.HasType || isVar); if (isVar) { if (this.IsConst) { diagnosticsForFirstDeclarator.Add(ErrorCode.ERR_ImplicitlyTypedVariableCannotBeConst, typeSyntax.Location); } if (fieldsBeingBound.ContainsReference(this)) { diagnostics.Add(ErrorCode.ERR_RecursivelyTypedVariable, this.ErrorLocation, this); type = default; } else if (fieldSyntax.Declaration.Variables.Count > 1) { diagnosticsForFirstDeclarator.Add(ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, typeSyntax.Location); } else if (this.IsConst && this.ContainingType.IsScriptClass) { // For const var in script, we won't try to bind the initializer (case below), as it can lead to an unbound recursion type = default; } else { fieldsBeingBound = new ConsList<FieldSymbol>(this, fieldsBeingBound); var syntaxNode = (EqualsValueClauseSyntax)declarator.Initializer; var initializerBinder = new ImplicitlyTypedFieldBinder(binder, fieldsBeingBound); var executableBinder = new ExecutableCodeBinder(syntaxNode, this, initializerBinder); var initializerOpt = executableBinder.BindInferredVariableInitializer(diagnostics, RefKind.None, syntaxNode, declarator); if (initializerOpt != null) { if ((object)initializerOpt.Type != null && !initializerOpt.Type.IsErrorType()) { type = TypeWithAnnotations.Create(initializerOpt.Type); } _lazyFieldTypeInferred = 1; } } if (!type.HasType) { type = TypeWithAnnotations.Create(binder.CreateErrorType("var")); } } } if (IsFixedSizeBuffer) { type = TypeWithAnnotations.Create(new PointerTypeSymbol(type)); if (ContainingType.TypeKind != TypeKind.Struct) { diagnostics.Add(ErrorCode.ERR_FixedNotInStruct, ErrorLocation); } var elementType = ((PointerTypeSymbol)type.Type).PointedAtType; int elementSize = elementType.FixedBufferElementSizeInBytes(); if (elementSize == 0) { var loc = typeSyntax.Location; diagnostics.Add(ErrorCode.ERR_IllegalFixedType, loc); } if (!binder.InUnsafeRegion) { diagnosticsForFirstDeclarator.Add(ErrorCode.ERR_UnsafeNeeded, declarator.Location); } } } Debug.Assert(type.DefaultType.IsPointerOrFunctionPointer() == IsPointerFieldSyntactically()); // update the lazyType only if it contains value last seen by the current thread: if (Interlocked.CompareExchange(ref _lazyType, new TypeWithAnnotations.Boxed(type.WithModifiers(this.RequiredCustomModifiers)), null) == null) { TypeChecks(type.Type, diagnostics); // CONSIDER: SourceEventFieldSymbol would like to suppress these diagnostics. AddDeclarationDiagnostics(diagnostics); bool isFirstDeclarator = fieldSyntax.Declaration.Variables[0] == declarator; if (isFirstDeclarator) { AddDeclarationDiagnostics(diagnosticsForFirstDeclarator); } state.NotePartComplete(CompletionPart.Type); } diagnostics.Free(); diagnosticsForFirstDeclarator.Free(); return _lazyType.Value; } internal bool FieldTypeInferred(ConsList<FieldSymbol> fieldsBeingBound) { if (!ContainingType.IsScriptClass) { return false; } GetFieldType(fieldsBeingBound); // lazyIsImplicitlyTypedField can only transition from value 0 to 1: return _lazyFieldTypeInferred != 0 || Volatile.Read(ref _lazyFieldTypeInferred) != 0; } protected sealed override ConstantValue MakeConstantValue(HashSet<SourceFieldSymbolWithSyntaxReference> dependencies, bool earlyDecodingWellKnownAttributes, BindingDiagnosticBag diagnostics) { if (!this.IsConst || VariableDeclaratorNode.Initializer == null) { return null; } return ConstantValueUtils.EvaluateFieldConstant(this, (EqualsValueClauseSyntax)VariableDeclaratorNode.Initializer, dependencies, earlyDecodingWellKnownAttributes, diagnostics); } internal override bool IsDefinedInSourceTree(SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken = default(CancellationToken)) { if (this.SyntaxTree == tree) { if (!definedWithinSpan.HasValue) { return true; } var fieldDeclaration = GetFieldDeclaration(this.SyntaxNode); return fieldDeclaration.SyntaxTree.HasCompilationUnitRoot && fieldDeclaration.Span.IntersectsWith(definedWithinSpan.Value); } return false; } internal override void AfterAddingTypeMembersChecks(ConversionsBase conversions, BindingDiagnosticBag diagnostics) { // This check prevents redundant ManagedAddr diagnostics on the underlying pointer field of a fixed-size buffer if (!IsFixedSizeBuffer) { Type.CheckAllConstraints(DeclaringCompilation, conversions, ErrorLocation, diagnostics); } base.AfterAddingTypeMembersChecks(conversions, 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 Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal abstract class SourceMemberFieldSymbol : SourceFieldSymbolWithSyntaxReference { private readonly DeclarationModifiers _modifiers; internal SourceMemberFieldSymbol( SourceMemberContainerTypeSymbol containingType, DeclarationModifiers modifiers, string name, SyntaxReference syntax, Location location) : base(containingType, name, syntax, location) { _modifiers = modifiers; } protected sealed override DeclarationModifiers Modifiers { get { return _modifiers; } } protected abstract TypeSyntax TypeSyntax { get; } protected abstract SyntaxTokenList ModifiersTokenList { get; } protected void TypeChecks(TypeSymbol type, BindingDiagnosticBag diagnostics) { if (type.IsStatic) { // Cannot declare a variable of static type '{0}' diagnostics.Add(ErrorCode.ERR_VarDeclIsStaticClass, this.ErrorLocation, type); } else if (type.IsVoidType()) { diagnostics.Add(ErrorCode.ERR_FieldCantHaveVoidType, TypeSyntax?.Location ?? this.Locations[0]); } else if (type.IsRestrictedType(ignoreSpanLikeTypes: true)) { diagnostics.Add(ErrorCode.ERR_FieldCantBeRefAny, TypeSyntax?.Location ?? this.Locations[0], type); } else if (type.IsRefLikeType && (this.IsStatic || !containingType.IsRefLikeType)) { diagnostics.Add(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, TypeSyntax?.Location ?? this.Locations[0], type); } else if (IsConst && !type.CanBeConst()) { SyntaxToken constToken = default(SyntaxToken); foreach (var modifier in ModifiersTokenList) { if (modifier.Kind() == SyntaxKind.ConstKeyword) { constToken = modifier; break; } } Debug.Assert(constToken.Kind() == SyntaxKind.ConstKeyword); diagnostics.Add(ErrorCode.ERR_BadConstType, constToken.GetLocation(), type); } else if (IsVolatile && !type.IsValidVolatileFieldType()) { // '{0}': a volatile field cannot be of the type '{1}' diagnostics.Add(ErrorCode.ERR_VolatileStruct, this.ErrorLocation, this, type); } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly); if (!this.IsNoMoreVisibleThan(type, ref useSiteInfo)) { // Inconsistent accessibility: field type '{1}' is less accessible than field '{0}' diagnostics.Add(ErrorCode.ERR_BadVisFieldType, this.ErrorLocation, this, type); } diagnostics.Add(this.ErrorLocation, useSiteInfo); } public abstract bool HasInitializer { get; } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); var compilation = this.DeclaringCompilation; var value = this.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false); // Synthesize DecimalConstantAttribute when the default value is of type decimal if (this.IsConst && value != null && this.Type.SpecialType == SpecialType.System_Decimal) { var data = GetDecodedWellKnownAttributeData(); if (data == null || data.ConstValue == CodeAnalysis.ConstantValue.Unset) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDecimalConstantAttribute(value.DecimalValue)); } } } public override Symbol AssociatedSymbol { get { return null; } } public override int FixedSize { get { Debug.Assert(!this.IsFixedSizeBuffer, "Subclasses representing fixed fields must override"); state.NotePartComplete(CompletionPart.FixedSize); return 0; } } internal static DeclarationModifiers MakeModifiers(NamedTypeSymbol containingType, SyntaxToken firstIdentifier, SyntaxTokenList modifiers, BindingDiagnosticBag diagnostics, out bool modifierErrors) { DeclarationModifiers defaultAccess = (containingType.IsInterface) ? DeclarationModifiers.Public : DeclarationModifiers.Private; DeclarationModifiers allowedModifiers = DeclarationModifiers.AccessibilityMask | DeclarationModifiers.Const | DeclarationModifiers.New | DeclarationModifiers.ReadOnly | DeclarationModifiers.Static | DeclarationModifiers.Volatile | DeclarationModifiers.Fixed | DeclarationModifiers.Unsafe | DeclarationModifiers.Abstract; // filtered out later var errorLocation = new SourceLocation(firstIdentifier); DeclarationModifiers result = ModifierUtils.MakeAndCheckNontypeMemberModifiers( modifiers, defaultAccess, allowedModifiers, errorLocation, diagnostics, out modifierErrors); if ((result & DeclarationModifiers.Abstract) != 0) { diagnostics.Add(ErrorCode.ERR_AbstractField, errorLocation); result &= ~DeclarationModifiers.Abstract; } if ((result & DeclarationModifiers.Fixed) != 0) { if ((result & DeclarationModifiers.Static) != 0) { // The modifier 'static' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.StaticKeyword)); } if ((result & DeclarationModifiers.ReadOnly) != 0) { // The modifier 'readonly' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.ReadOnlyKeyword)); } if ((result & DeclarationModifiers.Const) != 0) { // The modifier 'const' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.ConstKeyword)); } if ((result & DeclarationModifiers.Volatile) != 0) { // The modifier 'volatile' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.VolatileKeyword)); } result &= ~(DeclarationModifiers.Static | DeclarationModifiers.ReadOnly | DeclarationModifiers.Const | DeclarationModifiers.Volatile); Debug.Assert((result & ~(DeclarationModifiers.AccessibilityMask | DeclarationModifiers.Fixed | DeclarationModifiers.Unsafe | DeclarationModifiers.New)) == 0); } if ((result & DeclarationModifiers.Const) != 0) { if ((result & DeclarationModifiers.Static) != 0) { // The constant '{0}' cannot be marked static diagnostics.Add(ErrorCode.ERR_StaticConstant, errorLocation, firstIdentifier.ValueText); } if ((result & DeclarationModifiers.ReadOnly) != 0) { // The modifier 'readonly' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.ReadOnlyKeyword)); } if ((result & DeclarationModifiers.Volatile) != 0) { // The modifier 'volatile' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.VolatileKeyword)); } if ((result & DeclarationModifiers.Unsafe) != 0) { // The modifier 'unsafe' is not valid for this item diagnostics.Add(ErrorCode.ERR_BadMemberFlag, errorLocation, SyntaxFacts.GetText(SyntaxKind.UnsafeKeyword)); } result |= DeclarationModifiers.Static; // "constants are considered static members" } else { // NOTE: always cascading on a const, so suppress. // NOTE: we're being a bit sneaky here - we're using the containingType rather than this symbol // to determine whether or not unsafe is allowed. Since this symbol and the containing type are // in the same compilation, it won't make a difference. We do, however, have to pass the error // location explicitly. containingType.CheckUnsafeModifier(result, errorLocation, diagnostics); } return result; } internal sealed override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { while (true) { cancellationToken.ThrowIfCancellationRequested(); var incompletePart = state.NextIncompletePart; switch (incompletePart) { case CompletionPart.Attributes: GetAttributes(); break; case CompletionPart.Type: GetFieldType(ConsList<FieldSymbol>.Empty); break; case CompletionPart.FixedSize: int discarded = this.FixedSize; break; case CompletionPart.ConstantValue: GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false); break; case CompletionPart.None: return; default: // any other values are completion parts intended for other kinds of symbols state.NotePartComplete(CompletionPart.All & ~CompletionPart.FieldSymbolAll); break; } state.SpinWaitComplete(incompletePart, cancellationToken); } } internal override NamedTypeSymbol FixedImplementationType(PEModuleBuilder emitModule) { Debug.Assert(!this.IsFixedSizeBuffer, "Subclasses representing fixed fields must override"); return null; } } internal class SourceMemberFieldSymbolFromDeclarator : SourceMemberFieldSymbol { private readonly bool _hasInitializer; private TypeWithAnnotations.Boxed _lazyType; // Non-zero if the type of the field has been inferred from the type of its initializer expression // and the errors of binding the initializer have been or are being reported to compilation diagnostics. private int _lazyFieldTypeInferred; internal SourceMemberFieldSymbolFromDeclarator( SourceMemberContainerTypeSymbol containingType, VariableDeclaratorSyntax declarator, DeclarationModifiers modifiers, bool modifierErrors, BindingDiagnosticBag diagnostics) : base(containingType, modifiers, declarator.Identifier.ValueText, declarator.GetReference(), declarator.Identifier.GetLocation()) { _hasInitializer = declarator.Initializer != null; this.CheckAccessibility(diagnostics); if (!modifierErrors) { this.ReportModifiersDiagnostics(diagnostics); } if (containingType.IsInterface) { if (this.IsStatic) { Binder.CheckFeatureAvailability(declarator, MessageID.IDS_DefaultInterfaceImplementation, diagnostics, ErrorLocation); if (!ContainingAssembly.RuntimeSupportsDefaultInterfaceImplementation) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, ErrorLocation); } } else { diagnostics.Add(ErrorCode.ERR_InterfacesCantContainFields, ErrorLocation); } } } protected sealed override TypeSyntax TypeSyntax { get { return GetFieldDeclaration(VariableDeclaratorNode).Declaration.Type; } } protected sealed override SyntaxTokenList ModifiersTokenList { get { return GetFieldDeclaration(VariableDeclaratorNode).Modifiers; } } public sealed override bool HasInitializer { get { return _hasInitializer; } } protected VariableDeclaratorSyntax VariableDeclaratorNode { get { return (VariableDeclaratorSyntax)this.SyntaxNode; } } private static BaseFieldDeclarationSyntax GetFieldDeclaration(CSharpSyntaxNode declarator) { return (BaseFieldDeclarationSyntax)declarator.Parent.Parent; } protected override SyntaxList<AttributeListSyntax> AttributeDeclarationSyntaxList { get { if (this.containingType.AnyMemberHasAttributes) { return GetFieldDeclaration(this.SyntaxNode).AttributeLists; } return default(SyntaxList<AttributeListSyntax>); } } internal override bool HasPointerType { get { if (_lazyType != null) { bool isPointerType = _lazyType.Value.DefaultType.Kind switch { SymbolKind.PointerType => true, SymbolKind.FunctionPointerType => true, _ => false }; Debug.Assert(isPointerType == IsPointerFieldSyntactically()); return isPointerType; } return IsPointerFieldSyntactically(); } } private bool IsPointerFieldSyntactically() { var declaration = GetFieldDeclaration(VariableDeclaratorNode).Declaration; if (declaration.Type.Kind() switch { SyntaxKind.PointerType => true, SyntaxKind.FunctionPointerType => true, _ => false }) { // public int * Blah; // pointer return true; } return IsFixedSizeBuffer; } internal sealed override TypeWithAnnotations GetFieldType(ConsList<FieldSymbol> fieldsBeingBound) { Debug.Assert(fieldsBeingBound != null); if (_lazyType != null) { return _lazyType.Value; } var declarator = VariableDeclaratorNode; var fieldSyntax = GetFieldDeclaration(declarator); var typeSyntax = fieldSyntax.Declaration.Type; var compilation = this.DeclaringCompilation; var diagnostics = BindingDiagnosticBag.GetInstance(); TypeWithAnnotations type; // When we have multiple declarators, we report the type diagnostics on only the first. var diagnosticsForFirstDeclarator = BindingDiagnosticBag.GetInstance(); Symbol associatedPropertyOrEvent = this.AssociatedSymbol; if ((object)associatedPropertyOrEvent != null && associatedPropertyOrEvent.Kind == SymbolKind.Event) { EventSymbol @event = (EventSymbol)associatedPropertyOrEvent; if (@event.IsWindowsRuntimeEvent) { NamedTypeSymbol tokenTableType = this.DeclaringCompilation.GetWellKnownType(WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T); Binder.ReportUseSite(tokenTableType, diagnosticsForFirstDeclarator, this.ErrorLocation); // CONSIDER: Do we want to guard against the possibility that someone has created their own EventRegistrationTokenTable<T> // type that has additional generic constraints? type = TypeWithAnnotations.Create(tokenTableType.Construct(ImmutableArray.Create(@event.TypeWithAnnotations))); } else { type = @event.TypeWithAnnotations; } } else { var binderFactory = compilation.GetBinderFactory(SyntaxTree); var binder = binderFactory.GetBinder(typeSyntax); binder = binder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this); if (!ContainingType.IsScriptClass) { type = binder.BindType(typeSyntax, diagnosticsForFirstDeclarator); } else { bool isVar; type = binder.BindTypeOrVarKeyword(typeSyntax, diagnostics, out isVar); Debug.Assert(type.HasType || isVar); if (isVar) { if (this.IsConst) { diagnosticsForFirstDeclarator.Add(ErrorCode.ERR_ImplicitlyTypedVariableCannotBeConst, typeSyntax.Location); } if (fieldsBeingBound.ContainsReference(this)) { diagnostics.Add(ErrorCode.ERR_RecursivelyTypedVariable, this.ErrorLocation, this); type = default; } else if (fieldSyntax.Declaration.Variables.Count > 1) { diagnosticsForFirstDeclarator.Add(ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, typeSyntax.Location); } else if (this.IsConst && this.ContainingType.IsScriptClass) { // For const var in script, we won't try to bind the initializer (case below), as it can lead to an unbound recursion type = default; } else { fieldsBeingBound = new ConsList<FieldSymbol>(this, fieldsBeingBound); var syntaxNode = (EqualsValueClauseSyntax)declarator.Initializer; var initializerBinder = new ImplicitlyTypedFieldBinder(binder, fieldsBeingBound); var executableBinder = new ExecutableCodeBinder(syntaxNode, this, initializerBinder); var initializerOpt = executableBinder.BindInferredVariableInitializer(diagnostics, RefKind.None, syntaxNode, declarator); if (initializerOpt != null) { if ((object)initializerOpt.Type != null && !initializerOpt.Type.IsErrorType()) { type = TypeWithAnnotations.Create(initializerOpt.Type); } _lazyFieldTypeInferred = 1; } } if (!type.HasType) { type = TypeWithAnnotations.Create(binder.CreateErrorType("var")); } } } if (IsFixedSizeBuffer) { type = TypeWithAnnotations.Create(new PointerTypeSymbol(type)); if (ContainingType.TypeKind != TypeKind.Struct) { diagnostics.Add(ErrorCode.ERR_FixedNotInStruct, ErrorLocation); } var elementType = ((PointerTypeSymbol)type.Type).PointedAtType; int elementSize = elementType.FixedBufferElementSizeInBytes(); if (elementSize == 0) { var loc = typeSyntax.Location; diagnostics.Add(ErrorCode.ERR_IllegalFixedType, loc); } if (!binder.InUnsafeRegion) { diagnosticsForFirstDeclarator.Add(ErrorCode.ERR_UnsafeNeeded, declarator.Location); } } } Debug.Assert(type.DefaultType.IsPointerOrFunctionPointer() == IsPointerFieldSyntactically()); // update the lazyType only if it contains value last seen by the current thread: if (Interlocked.CompareExchange(ref _lazyType, new TypeWithAnnotations.Boxed(type.WithModifiers(this.RequiredCustomModifiers)), null) == null) { TypeChecks(type.Type, diagnostics); // CONSIDER: SourceEventFieldSymbol would like to suppress these diagnostics. AddDeclarationDiagnostics(diagnostics); bool isFirstDeclarator = fieldSyntax.Declaration.Variables[0] == declarator; if (isFirstDeclarator) { AddDeclarationDiagnostics(diagnosticsForFirstDeclarator); } state.NotePartComplete(CompletionPart.Type); } diagnostics.Free(); diagnosticsForFirstDeclarator.Free(); return _lazyType.Value; } internal bool FieldTypeInferred(ConsList<FieldSymbol> fieldsBeingBound) { if (!ContainingType.IsScriptClass) { return false; } GetFieldType(fieldsBeingBound); // lazyIsImplicitlyTypedField can only transition from value 0 to 1: return _lazyFieldTypeInferred != 0 || Volatile.Read(ref _lazyFieldTypeInferred) != 0; } protected sealed override ConstantValue MakeConstantValue(HashSet<SourceFieldSymbolWithSyntaxReference> dependencies, bool earlyDecodingWellKnownAttributes, BindingDiagnosticBag diagnostics) { if (!this.IsConst || VariableDeclaratorNode.Initializer == null) { return null; } return ConstantValueUtils.EvaluateFieldConstant(this, (EqualsValueClauseSyntax)VariableDeclaratorNode.Initializer, dependencies, earlyDecodingWellKnownAttributes, diagnostics); } internal override bool IsDefinedInSourceTree(SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken = default(CancellationToken)) { if (this.SyntaxTree == tree) { if (!definedWithinSpan.HasValue) { return true; } var fieldDeclaration = GetFieldDeclaration(this.SyntaxNode); return fieldDeclaration.SyntaxTree.HasCompilationUnitRoot && fieldDeclaration.Span.IntersectsWith(definedWithinSpan.Value); } return false; } internal override void AfterAddingTypeMembersChecks(ConversionsBase conversions, BindingDiagnosticBag diagnostics) { // This check prevents redundant ManagedAddr diagnostics on the underlying pointer field of a fixed-size buffer if (!IsFixedSizeBuffer) { Type.CheckAllConstraints(DeclaringCompilation, conversions, ErrorLocation, diagnostics); } base.AfterAddingTypeMembersChecks(conversions, diagnostics); } } }
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/Differencing/EditScript.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis.Differencing { /// <summary> /// Represents a sequence of tree edits. /// </summary> public sealed partial class EditScript<TNode> { private readonly Match<TNode> _match; private readonly ImmutableArray<Edit<TNode>> _edits; internal EditScript(Match<TNode> match) { _match = match; var edits = new List<Edit<TNode>>(); AddUpdatesInsertsMoves(edits); AddDeletes(edits); _edits = edits.AsImmutable(); } public ImmutableArray<Edit<TNode>> Edits => _edits; public Match<TNode> Match => _match; private TreeComparer<TNode> Comparer => _match.Comparer; private TNode Root1 => _match.OldRoot; private TNode Root2 => _match.NewRoot; private void AddUpdatesInsertsMoves(List<Edit<TNode>> edits) { // Breadth-first traversal. ProcessNode(edits, Root2); var rootChildren = Comparer.GetChildren(Root2); if (rootChildren == null) { return; } var queue = new Queue<IEnumerable<TNode>>(); queue.Enqueue(rootChildren); do { var children = queue.Dequeue(); foreach (var child in children) { ProcessNode(edits, child); var grandChildren = Comparer.GetChildren(child); if (grandChildren != null) { queue.Enqueue(grandChildren); } } } while (queue.Count > 0); } private void ProcessNode(List<Edit<TNode>> edits, TNode x) { Debug.Assert(Comparer.TreesEqual(x, Root2)); // NOTE: // Our implementation differs from the algorithm described in the paper in following: // - We don't update M' and T1 since we don't need the final matching and the transformed tree. // - Insert and Move edits don't need to store the offset of the nodes relative to their parents, // so we don't calculate those. Thus we don't need to implement FindPos. // - We don't mark nodes "in order" since the marks are only needed by FindPos. // a) // Let x be the current node in the breadth-first search of T2. // Let y = parent(x). // Let z be the partner of parent(x) in M'. (note: we don't need z for insert) // // NOTE: // If we needed z then we would need to be updating M' as we encounter insertions. var hasPartner = _match.TryGetPartnerInTree1(x, out var w); var hasParent = Comparer.TryGetParent(x, out var y); if (!hasPartner) { // b) If x has no partner in M'. // i. k := FindPos(x) // ii. Append INS((w, a, value(x)), z, k) to E for a new identifier w. // iii. Add (w, x) to M' and apply INS((w, a, value(x)), z, k) to T1. edits.Add(new Edit<TNode>(EditKind.Insert, Comparer, oldNode: default, newNode: x)); // NOTE: // We don't update M' here. } else if (hasParent) { // c) else if x is not a root // i. Let w be the partner of x in M', and let v = parent(w) in T1. var v = Comparer.GetParent(w); // ii. if value(w) != value(x) // A. Append UPD(w, value(x)) to E // B. Apply UPD(w, value(x) to T1 // Let the Comparer decide whether an update should be added to the edit list. // The Comparer defines what changes in node values it cares about. if (!Comparer.ValuesEqual(w, x)) { edits.Add(new Edit<TNode>(EditKind.Update, Comparer, oldNode: w, newNode: x)); } // If parents of w and x don't match, it's a move. // iii. if not (v, y) in M' // NOTE: The paper says (y, v) but that seems wrong since M': T1 -> T2 and w,v in T1 and x,y in T2. if (!_match.Contains(v, y)) { // A. Let z be the partner of y in M'. (NOTE: z not needed) // B. k := FindPos(x) // C. Append MOV(w, z, k) // D. Apply MOV(w, z, k) to T1 edits.Add(new Edit<TNode>(EditKind.Move, Comparer, oldNode: w, newNode: x)); } } // d) AlignChildren(w, x) // NOTE: If we just applied an INS((w, a, value(x)), z, k) operation on tree T1 // the newly created node w would have no children. So there is nothing to align. if (hasPartner) { AlignChildren(edits, w, x); } } private void AddDeletes(List<Edit<TNode>> edits) { // 3. Do a post-order traversal of T1. // a) Let w be the current node in the post-order traversal of T1. // b) If w has no partner in M' then append DEL(w) to E and apply DEL(w) to T1. // // NOTE: The fact that we haven't updated M' during the Insert phase // doesn't affect Delete phase. The original algorithm inserted new node n1 into T1 // when an insertion INS(n1, n2) was detected. It also added (n1, n2) to M'. // Then in Delete phase n1 is visited but nothing is done since it has a partner n2 in M'. // Since we don't add n1 into T1, not adding (n1, n2) to M' doesn't affect the Delete phase. foreach (var w in Comparer.GetDescendants(Root1)) { if (!_match.HasPartnerInTree2(w)) { edits.Add(new Edit<TNode>(EditKind.Delete, Comparer, oldNode: w, newNode: default)); } } } private void AlignChildren(List<Edit<TNode>> edits, TNode w, TNode x) { Debug.Assert(Comparer.TreesEqual(w, Root1)); Debug.Assert(Comparer.TreesEqual(x, Root2)); IEnumerable<TNode> wChildren, xChildren; if ((wChildren = Comparer.GetChildren(w)) == null || (xChildren = Comparer.GetChildren(x)) == null) { return; } // Step 1 // Make all children of w and all children x "out of order" // NOTE: We don't need to mark nodes "in order". // Step 2 // Let S1 be the sequence of children of w whose partner are children // of x and let S2 be the sequence of children of x whose partner are // children of w. List<TNode> s1 = null; foreach (var e in wChildren) { if (_match.TryGetPartnerInTree2(e, out var pw) && Comparer.GetParent(pw).Equals(x)) { if (s1 == null) { s1 = new List<TNode>(); } s1.Add(e); } } List<TNode> s2 = null; foreach (var e in xChildren) { if (_match.TryGetPartnerInTree1(e, out var px) && Comparer.GetParent(px).Equals(w)) { if (s2 == null) { s2 = new List<TNode>(); } s2.Add(e); } } if (s1 == null || s2 == null) { return; } // Step 3, 4 // Define the function Equal(a,b) to be true if and only if (a,c) in M' // Let S <- LCS(S1, S2, Equal) var lcs = new Match<TNode>.LongestCommonSubsequence(_match); var s = lcs.GetMatchingNodes(s1, s2); // Step 5 // For each (a,b) in S, mark nodes a and b "in order" // NOTE: We don't need to mark nodes "in order". // Step 6 // For each a in S1, b in S2 such that (a,b) in M but (a,b) not in S // (a) k <- FindPos(b) // (b) Append MOV(a,w,k) to E and apply MOV(a,w,k) to T1 // (c) Mark a and b "in order" // NOTE: We don't mark nodes "in order". foreach (var a in s1) { // (a,b) in M // => b in S2 since S2 == { b | parent(b) == x && parent(partner(b)) == w } // (a,b) not in S if (_match.TryGetPartnerInTree2(a, out var b) && Comparer.GetParent(b).Equals(x) && !ContainsPair(s, a, b)) { Debug.Assert(Comparer.TreesEqual(a, Root1)); Debug.Assert(Comparer.TreesEqual(b, Root2)); edits.Add(new Edit<TNode>(EditKind.Reorder, Comparer, oldNode: a, newNode: b)); } } } private static bool ContainsPair(Dictionary<TNode, TNode> dict, TNode a, TNode b) => dict.TryGetValue(a, out var value) && value.Equals(b); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis.Differencing { /// <summary> /// Represents a sequence of tree edits. /// </summary> public sealed partial class EditScript<TNode> { private readonly Match<TNode> _match; private readonly ImmutableArray<Edit<TNode>> _edits; internal EditScript(Match<TNode> match) { _match = match; var edits = new List<Edit<TNode>>(); AddUpdatesInsertsMoves(edits); AddDeletes(edits); _edits = edits.AsImmutable(); } public ImmutableArray<Edit<TNode>> Edits => _edits; public Match<TNode> Match => _match; private TreeComparer<TNode> Comparer => _match.Comparer; private TNode Root1 => _match.OldRoot; private TNode Root2 => _match.NewRoot; private void AddUpdatesInsertsMoves(List<Edit<TNode>> edits) { // Breadth-first traversal. ProcessNode(edits, Root2); var rootChildren = Comparer.GetChildren(Root2); if (rootChildren == null) { return; } var queue = new Queue<IEnumerable<TNode>>(); queue.Enqueue(rootChildren); do { var children = queue.Dequeue(); foreach (var child in children) { ProcessNode(edits, child); var grandChildren = Comparer.GetChildren(child); if (grandChildren != null) { queue.Enqueue(grandChildren); } } } while (queue.Count > 0); } private void ProcessNode(List<Edit<TNode>> edits, TNode x) { Debug.Assert(Comparer.TreesEqual(x, Root2)); // NOTE: // Our implementation differs from the algorithm described in the paper in following: // - We don't update M' and T1 since we don't need the final matching and the transformed tree. // - Insert and Move edits don't need to store the offset of the nodes relative to their parents, // so we don't calculate those. Thus we don't need to implement FindPos. // - We don't mark nodes "in order" since the marks are only needed by FindPos. // a) // Let x be the current node in the breadth-first search of T2. // Let y = parent(x). // Let z be the partner of parent(x) in M'. (note: we don't need z for insert) // // NOTE: // If we needed z then we would need to be updating M' as we encounter insertions. var hasPartner = _match.TryGetPartnerInTree1(x, out var w); var hasParent = Comparer.TryGetParent(x, out var y); if (!hasPartner) { // b) If x has no partner in M'. // i. k := FindPos(x) // ii. Append INS((w, a, value(x)), z, k) to E for a new identifier w. // iii. Add (w, x) to M' and apply INS((w, a, value(x)), z, k) to T1. edits.Add(new Edit<TNode>(EditKind.Insert, Comparer, oldNode: default, newNode: x)); // NOTE: // We don't update M' here. } else if (hasParent) { // c) else if x is not a root // i. Let w be the partner of x in M', and let v = parent(w) in T1. var v = Comparer.GetParent(w); // ii. if value(w) != value(x) // A. Append UPD(w, value(x)) to E // B. Apply UPD(w, value(x) to T1 // Let the Comparer decide whether an update should be added to the edit list. // The Comparer defines what changes in node values it cares about. if (!Comparer.ValuesEqual(w, x)) { edits.Add(new Edit<TNode>(EditKind.Update, Comparer, oldNode: w, newNode: x)); } // If parents of w and x don't match, it's a move. // iii. if not (v, y) in M' // NOTE: The paper says (y, v) but that seems wrong since M': T1 -> T2 and w,v in T1 and x,y in T2. if (!_match.Contains(v, y)) { // A. Let z be the partner of y in M'. (NOTE: z not needed) // B. k := FindPos(x) // C. Append MOV(w, z, k) // D. Apply MOV(w, z, k) to T1 edits.Add(new Edit<TNode>(EditKind.Move, Comparer, oldNode: w, newNode: x)); } } // d) AlignChildren(w, x) // NOTE: If we just applied an INS((w, a, value(x)), z, k) operation on tree T1 // the newly created node w would have no children. So there is nothing to align. if (hasPartner) { AlignChildren(edits, w, x); } } private void AddDeletes(List<Edit<TNode>> edits) { // 3. Do a post-order traversal of T1. // a) Let w be the current node in the post-order traversal of T1. // b) If w has no partner in M' then append DEL(w) to E and apply DEL(w) to T1. // // NOTE: The fact that we haven't updated M' during the Insert phase // doesn't affect Delete phase. The original algorithm inserted new node n1 into T1 // when an insertion INS(n1, n2) was detected. It also added (n1, n2) to M'. // Then in Delete phase n1 is visited but nothing is done since it has a partner n2 in M'. // Since we don't add n1 into T1, not adding (n1, n2) to M' doesn't affect the Delete phase. foreach (var w in Comparer.GetDescendants(Root1)) { if (!_match.HasPartnerInTree2(w)) { edits.Add(new Edit<TNode>(EditKind.Delete, Comparer, oldNode: w, newNode: default)); } } } private void AlignChildren(List<Edit<TNode>> edits, TNode w, TNode x) { Debug.Assert(Comparer.TreesEqual(w, Root1)); Debug.Assert(Comparer.TreesEqual(x, Root2)); IEnumerable<TNode> wChildren, xChildren; if ((wChildren = Comparer.GetChildren(w)) == null || (xChildren = Comparer.GetChildren(x)) == null) { return; } // Step 1 // Make all children of w and all children x "out of order" // NOTE: We don't need to mark nodes "in order". // Step 2 // Let S1 be the sequence of children of w whose partner are children // of x and let S2 be the sequence of children of x whose partner are // children of w. List<TNode> s1 = null; foreach (var e in wChildren) { if (_match.TryGetPartnerInTree2(e, out var pw) && Comparer.GetParent(pw).Equals(x)) { if (s1 == null) { s1 = new List<TNode>(); } s1.Add(e); } } List<TNode> s2 = null; foreach (var e in xChildren) { if (_match.TryGetPartnerInTree1(e, out var px) && Comparer.GetParent(px).Equals(w)) { if (s2 == null) { s2 = new List<TNode>(); } s2.Add(e); } } if (s1 == null || s2 == null) { return; } // Step 3, 4 // Define the function Equal(a,b) to be true if and only if (a,c) in M' // Let S <- LCS(S1, S2, Equal) var lcs = new Match<TNode>.LongestCommonSubsequence(_match); var s = lcs.GetMatchingNodes(s1, s2); // Step 5 // For each (a,b) in S, mark nodes a and b "in order" // NOTE: We don't need to mark nodes "in order". // Step 6 // For each a in S1, b in S2 such that (a,b) in M but (a,b) not in S // (a) k <- FindPos(b) // (b) Append MOV(a,w,k) to E and apply MOV(a,w,k) to T1 // (c) Mark a and b "in order" // NOTE: We don't mark nodes "in order". foreach (var a in s1) { // (a,b) in M // => b in S2 since S2 == { b | parent(b) == x && parent(partner(b)) == w } // (a,b) not in S if (_match.TryGetPartnerInTree2(a, out var b) && Comparer.GetParent(b).Equals(x) && !ContainsPair(s, a, b)) { Debug.Assert(Comparer.TreesEqual(a, Root1)); Debug.Assert(Comparer.TreesEqual(b, Root2)); edits.Add(new Edit<TNode>(EditKind.Reorder, Comparer, oldNode: a, newNode: b)); } } } private static bool ContainsPair(Dictionary<TNode, TNode> dict, TNode a, TNode b) => dict.TryGetValue(a, out var value) && value.Equals(b); } }
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/Symbols/SymbolVisitor.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 { public abstract class SymbolVisitor { public virtual void Visit(ISymbol? symbol) { symbol?.Accept(this); } public virtual void DefaultVisit(ISymbol symbol) { } public virtual void VisitAlias(IAliasSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitArrayType(IArrayTypeSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitAssembly(IAssemblySymbol symbol) { DefaultVisit(symbol); } public virtual void VisitDiscard(IDiscardSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitDynamicType(IDynamicTypeSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitEvent(IEventSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitField(IFieldSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitLabel(ILabelSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitLocal(ILocalSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitMethod(IMethodSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitModule(IModuleSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitNamedType(INamedTypeSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitNamespace(INamespaceSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitParameter(IParameterSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitPointerType(IPointerTypeSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitProperty(IPropertySymbol symbol) { DefaultVisit(symbol); } public virtual void VisitRangeVariable(IRangeVariableSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitTypeParameter(ITypeParameterSymbol symbol) { DefaultVisit(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. namespace Microsoft.CodeAnalysis { public abstract class SymbolVisitor { public virtual void Visit(ISymbol? symbol) { symbol?.Accept(this); } public virtual void DefaultVisit(ISymbol symbol) { } public virtual void VisitAlias(IAliasSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitArrayType(IArrayTypeSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitAssembly(IAssemblySymbol symbol) { DefaultVisit(symbol); } public virtual void VisitDiscard(IDiscardSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitDynamicType(IDynamicTypeSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitEvent(IEventSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitField(IFieldSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitLabel(ILabelSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitLocal(ILocalSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitMethod(IMethodSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitModule(IModuleSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitNamedType(INamedTypeSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitNamespace(INamespaceSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitParameter(IParameterSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitPointerType(IPointerTypeSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitProperty(IPropertySymbol symbol) { DefaultVisit(symbol); } public virtual void VisitRangeVariable(IRangeVariableSymbol symbol) { DefaultVisit(symbol); } public virtual void VisitTypeParameter(ITypeParameterSymbol symbol) { DefaultVisit(symbol); } } }
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/Formatting/Rules/IFormattingRule.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; namespace Microsoft.CodeAnalysis.Formatting.Rules { [Obsolete("This interface is no longer used")] internal interface IFormattingRule { } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis.Formatting.Rules { [Obsolete("This interface is no longer used")] internal interface IFormattingRule { } }
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Tools/BuildBoss/SolutionCheckerUtil.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; namespace BuildBoss { internal sealed class SolutionCheckerUtil : ICheckerUtil { private struct SolutionProjectData { internal ProjectEntry ProjectEntry; internal ProjectData ProjectData; internal SolutionProjectData(ProjectEntry entry, ProjectData data) { ProjectEntry = entry; ProjectData = data; } } internal string SolutionFilePath { get; } internal string SolutionPath { get; } internal bool IsPrimarySolution { get; } internal SolutionCheckerUtil(string solutionFilePath, bool isPrimarySolution) { SolutionFilePath = solutionFilePath; IsPrimarySolution = isPrimarySolution; SolutionPath = Path.GetDirectoryName(SolutionFilePath); } public bool Check(TextWriter textWriter) { var allGood = true; allGood &= CheckDuplicate(textWriter, out var map); allGood &= CheckProjects(textWriter, map); allGood &= CheckProjectSystemGuid(textWriter, map.Values); return allGood; } private bool CheckProjects(TextWriter textWriter, Dictionary<ProjectKey, SolutionProjectData> map) { var solutionMap = new Dictionary<ProjectKey, ProjectData>(); foreach (var pair in map) { solutionMap.Add(pair.Key, pair.Value.ProjectData); } var allGood = true; var count = 0; foreach (var data in map.Values.OrderBy(x => x.ProjectEntry.Name)) { var projectWriter = new StringWriter(); var projectData = data.ProjectData; projectWriter.WriteLine($"Processing {projectData.Key.FileName}"); var util = new ProjectCheckerUtil(projectData, solutionMap, IsPrimarySolution); if (!util.Check(projectWriter)) { allGood = false; textWriter.WriteLine(projectWriter.ToString()); } count++; } textWriter.WriteLine($"Processed {count} projects"); return allGood; } private bool CheckDuplicate(TextWriter textWriter, out Dictionary<ProjectKey, SolutionProjectData> map) { map = new Dictionary<ProjectKey, SolutionProjectData>(); var allGood = true; foreach (var projectEntry in SolutionUtil.ParseProjects(SolutionFilePath)) { if (projectEntry.IsFolder) { continue; } var projectFilePath = Path.Combine(SolutionPath, projectEntry.RelativeFilePath); var projectData = new ProjectData(projectFilePath); if (map.ContainsKey(projectData.Key)) { textWriter.WriteLine($"Duplicate project detected {projectData.FileName}"); allGood = false; } else { map.Add(projectData.Key, new SolutionProjectData(projectEntry, projectData)); } } return allGood; } /// <summary> /// Ensure solution files have the proper project system GUID. /// </summary> private bool CheckProjectSystemGuid(TextWriter textWriter, IEnumerable<SolutionProjectData> dataList) { Guid getExpectedGuid(ProjectData data) { var util = data.ProjectUtil; switch (ProjectEntryUtil.GetProjectFileType(data.FilePath)) { case ProjectFileType.CSharp: return ProjectEntryUtil.ManagedProjectSystemCSharp; case ProjectFileType.Basic: return ProjectEntryUtil.ManagedProjectSystemVisualBasic; case ProjectFileType.Shared: return ProjectEntryUtil.SharedProject; default: throw new Exception($"Invalid file path {data.FilePath}"); } } var allGood = true; foreach (var data in dataList.Where(x => x.ProjectEntry.ProjectType != ProjectFileType.Tool)) { var guid = getExpectedGuid(data.ProjectData); if (guid != data.ProjectEntry.TypeGuid) { var name = data.ProjectData.FileName; textWriter.WriteLine($"Project {name} should have GUID {guid} but has {data.ProjectEntry.TypeGuid}"); allGood = false; } } return allGood; } } }
// Licensed to the .NET Foundation under one or more 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; namespace BuildBoss { internal sealed class SolutionCheckerUtil : ICheckerUtil { private struct SolutionProjectData { internal ProjectEntry ProjectEntry; internal ProjectData ProjectData; internal SolutionProjectData(ProjectEntry entry, ProjectData data) { ProjectEntry = entry; ProjectData = data; } } internal string SolutionFilePath { get; } internal string SolutionPath { get; } internal bool IsPrimarySolution { get; } internal SolutionCheckerUtil(string solutionFilePath, bool isPrimarySolution) { SolutionFilePath = solutionFilePath; IsPrimarySolution = isPrimarySolution; SolutionPath = Path.GetDirectoryName(SolutionFilePath); } public bool Check(TextWriter textWriter) { var allGood = true; allGood &= CheckDuplicate(textWriter, out var map); allGood &= CheckProjects(textWriter, map); allGood &= CheckProjectSystemGuid(textWriter, map.Values); return allGood; } private bool CheckProjects(TextWriter textWriter, Dictionary<ProjectKey, SolutionProjectData> map) { var solutionMap = new Dictionary<ProjectKey, ProjectData>(); foreach (var pair in map) { solutionMap.Add(pair.Key, pair.Value.ProjectData); } var allGood = true; var count = 0; foreach (var data in map.Values.OrderBy(x => x.ProjectEntry.Name)) { var projectWriter = new StringWriter(); var projectData = data.ProjectData; projectWriter.WriteLine($"Processing {projectData.Key.FileName}"); var util = new ProjectCheckerUtil(projectData, solutionMap, IsPrimarySolution); if (!util.Check(projectWriter)) { allGood = false; textWriter.WriteLine(projectWriter.ToString()); } count++; } textWriter.WriteLine($"Processed {count} projects"); return allGood; } private bool CheckDuplicate(TextWriter textWriter, out Dictionary<ProjectKey, SolutionProjectData> map) { map = new Dictionary<ProjectKey, SolutionProjectData>(); var allGood = true; foreach (var projectEntry in SolutionUtil.ParseProjects(SolutionFilePath)) { if (projectEntry.IsFolder) { continue; } var projectFilePath = Path.Combine(SolutionPath, projectEntry.RelativeFilePath); var projectData = new ProjectData(projectFilePath); if (map.ContainsKey(projectData.Key)) { textWriter.WriteLine($"Duplicate project detected {projectData.FileName}"); allGood = false; } else { map.Add(projectData.Key, new SolutionProjectData(projectEntry, projectData)); } } return allGood; } /// <summary> /// Ensure solution files have the proper project system GUID. /// </summary> private bool CheckProjectSystemGuid(TextWriter textWriter, IEnumerable<SolutionProjectData> dataList) { Guid getExpectedGuid(ProjectData data) { var util = data.ProjectUtil; switch (ProjectEntryUtil.GetProjectFileType(data.FilePath)) { case ProjectFileType.CSharp: return ProjectEntryUtil.ManagedProjectSystemCSharp; case ProjectFileType.Basic: return ProjectEntryUtil.ManagedProjectSystemVisualBasic; case ProjectFileType.Shared: return ProjectEntryUtil.SharedProject; default: throw new Exception($"Invalid file path {data.FilePath}"); } } var allGood = true; foreach (var data in dataList.Where(x => x.ProjectEntry.ProjectType != ProjectFileType.Tool)) { var guid = getExpectedGuid(data.ProjectData); if (guid != data.ProjectEntry.TypeGuid) { var name = data.ProjectData.FileName; textWriter.WriteLine($"Project {name} should have GUID {guid} but has {data.ProjectEntry.TypeGuid}"); allGood = false; } } return allGood; } } }
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Lsif/GeneratorTest/HoverTests.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.Workspaces Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServer.Protocol Namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests <UseExportProvider> Public NotInheritable Class HoverTests Private Const TestProjectAssemblyName As String = "TestProject" <Theory> <InlineData("class [|C|] { string s; }")> <InlineData("class C { void [|M|]() { } }")> <InlineData("class C { string [|s|]; }")> <InlineData("class C { void M(string [|s|]) { M(s); } }")> <InlineData("class C { void M(string s) { string [|local|] = """"; } }")> <InlineData(" class C { /// <summary>Doc Comment</summary> void [|M|]() { } }")> Public Async Function TestDefinition(code As String) As Task Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync( TestWorkspace.CreateWorkspace( <Workspace> <Project Language="C#" AssemblyName=<%= TestProjectAssemblyName %> FilePath="Z:\TestProject.csproj" CommonReferences="true"> <Document Name="A.cs" FilePath="Z:\A.cs"> <%= code %> </Document> </Project> </Workspace>)) Dim rangeVertex = Await lsif.GetSelectedRangeAsync() Dim resultSetVertex = lsif.GetLinkedVertices(Of Graph.ResultSet)(rangeVertex, "next").Single() Dim hoverVertex = lsif.GetLinkedVertices(Of Graph.HoverResult)(resultSetVertex, Methods.TextDocumentHoverName).SingleOrDefault() Dim hoverMarkupContent = DirectCast(hoverVertex.Result.Contents.Value, MarkupContent) Dim expectedHoverContents As String Select Case code Case "class [|C|] { string s; }" expectedHoverContents = "class C" Case "class C { void [|M|]() { } }" expectedHoverContents = "void C.M()" Case "class C { string [|s|]; }" expectedHoverContents = $"({FeaturesResources.field}) string C.s" Case "class C { void M(string [|s|]) { M(s); } }" expectedHoverContents = $"({FeaturesResources.parameter}) string s" Case "class C { void M(string s) { string [|local|] = """"; } }" expectedHoverContents = $"({FeaturesResources.local_variable}) string local" Case " class C { /// <summary>Doc Comment</summary> void [|M|]() { } }" expectedHoverContents = "void C.M() Doc Comment" Case Else Throw TestExceptionUtilities.UnexpectedValue(code) End Select Assert.Equal(MarkupKind.PlainText, hoverMarkupContent.Kind) Assert.Equal(expectedHoverContents + Environment.NewLine, hoverMarkupContent.Value) End Function <Theory> <InlineData("class C { [|string|] s; }")> <InlineData("class C { void M() { [|M|](); } }")> <InlineData("class C { void M(string s) { M([|s|]); } }")> <InlineData("class C { void M(string s) { string local = """"; M([|local|]); } }")> <InlineData("using [|S|] = System.String;")> <InlineData("class C { [|global|]::System.String s; }")> <InlineData(" class C { /// <see cref=""C.[|M|]()"" /> void M() { } }")> Public Async Function TestReference(code As String) As Task Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync( TestWorkspace.CreateWorkspace( <Workspace> <Project Language="C#" AssemblyName=<%= TestProjectAssemblyName %> FilePath="Z:\TestProject.csproj" CommonReferences="true"> <Document Name="A.cs" FilePath="Z:\A.cs"> <%= code %> </Document> </Project> </Workspace>)) Dim rangeVertex = Await lsif.GetSelectedRangeAsync() Dim resultSetVertex = lsif.GetLinkedVertices(Of Graph.ResultSet)(rangeVertex, "next").Single() Dim hoverVertex = lsif.GetLinkedVertices(Of Graph.HoverResult)(resultSetVertex, Methods.TextDocumentHoverName).SingleOrDefault() Dim hoverMarkupContent = DirectCast(hoverVertex.Result.Contents.Value, MarkupContent) Dim expectedHoverContents As String Select Case code Case "class C { [|string|] s; }" expectedHoverContents = "class System.String" Case "class C { void M() { [|M|](); } }" expectedHoverContents = "void C.M()" Case "class C { void M(string s) { M([|s|]); } }" expectedHoverContents = $"({FeaturesResources.parameter}) string s" Case "class C { void M(string s) { string local = """"; M([|local|]); } }" expectedHoverContents = $"({FeaturesResources.local_variable}) string local" Case "using [|S|] = System.String;" expectedHoverContents = "class System.String" Case "class C { [|global|]::System.String s; }" expectedHoverContents = "<global namespace>" Case " class C { /// <see cref=""C.[|M|]()"" /> void M() { } }" expectedHoverContents = "void C.M()" Case Else Throw TestExceptionUtilities.UnexpectedValue(code) End Select Assert.Equal(MarkupKind.PlainText, hoverMarkupContent.Kind) Assert.Equal(expectedHoverContents + Environment.NewLine, hoverMarkupContent.Value) End Function <Fact> Public Async Function ToplevelResultsInMultipleFiles() As Task Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync( TestWorkspace.CreateWorkspace( <Workspace> <Project Language="C#" AssemblyName=<%= TestProjectAssemblyName %> FilePath="Z:\TestProject.csproj" CommonReferences="true"> <Document Name="A.cs" FilePath="Z:\A.cs"> class A { [|string|] s; } </Document> <Document Name="B.cs" FilePath="Z:\B.cs"> class B { [|string|] s; } </Document> <Document Name="C.cs" FilePath="Z:\C.cs"> class C { [|string|] s; } </Document> <Document Name="D.cs" FilePath="Z:\D.cs"> class D { [|string|] s; } </Document> <Document Name="E.cs" FilePath="Z:\E.cs"> class E { [|string|] s; } </Document> </Project> </Workspace>)) Dim hoverVertex As Graph.HoverResult = Nothing For Each rangeVertex In Await lsif.GetSelectedRangesAsync() Dim resultSetVertex = lsif.GetLinkedVertices(Of Graph.ResultSet)(rangeVertex, "next").Single() Dim vertex = lsif.GetLinkedVertices(Of Graph.HoverResult)(resultSetVertex, Methods.TextDocumentHoverName).Single() If hoverVertex Is Nothing Then hoverVertex = vertex Else Assert.Same(hoverVertex, vertex) End If Next Dim hoverMarkupContent = DirectCast(hoverVertex.Result.Contents.Value, MarkupContent) Assert.Equal(MarkupKind.PlainText, hoverMarkupContent.Kind) Assert.Equal("class System.String" + Environment.NewLine, hoverMarkupContent.Value) 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.Workspaces Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServer.Protocol Namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests <UseExportProvider> Public NotInheritable Class HoverTests Private Const TestProjectAssemblyName As String = "TestProject" <Theory> <InlineData("class [|C|] { string s; }")> <InlineData("class C { void [|M|]() { } }")> <InlineData("class C { string [|s|]; }")> <InlineData("class C { void M(string [|s|]) { M(s); } }")> <InlineData("class C { void M(string s) { string [|local|] = """"; } }")> <InlineData(" class C { /// <summary>Doc Comment</summary> void [|M|]() { } }")> Public Async Function TestDefinition(code As String) As Task Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync( TestWorkspace.CreateWorkspace( <Workspace> <Project Language="C#" AssemblyName=<%= TestProjectAssemblyName %> FilePath="Z:\TestProject.csproj" CommonReferences="true"> <Document Name="A.cs" FilePath="Z:\A.cs"> <%= code %> </Document> </Project> </Workspace>)) Dim rangeVertex = Await lsif.GetSelectedRangeAsync() Dim resultSetVertex = lsif.GetLinkedVertices(Of Graph.ResultSet)(rangeVertex, "next").Single() Dim hoverVertex = lsif.GetLinkedVertices(Of Graph.HoverResult)(resultSetVertex, Methods.TextDocumentHoverName).SingleOrDefault() Dim hoverMarkupContent = DirectCast(hoverVertex.Result.Contents.Value, MarkupContent) Dim expectedHoverContents As String Select Case code Case "class [|C|] { string s; }" expectedHoverContents = "class C" Case "class C { void [|M|]() { } }" expectedHoverContents = "void C.M()" Case "class C { string [|s|]; }" expectedHoverContents = $"({FeaturesResources.field}) string C.s" Case "class C { void M(string [|s|]) { M(s); } }" expectedHoverContents = $"({FeaturesResources.parameter}) string s" Case "class C { void M(string s) { string [|local|] = """"; } }" expectedHoverContents = $"({FeaturesResources.local_variable}) string local" Case " class C { /// <summary>Doc Comment</summary> void [|M|]() { } }" expectedHoverContents = "void C.M() Doc Comment" Case Else Throw TestExceptionUtilities.UnexpectedValue(code) End Select Assert.Equal(MarkupKind.PlainText, hoverMarkupContent.Kind) Assert.Equal(expectedHoverContents + Environment.NewLine, hoverMarkupContent.Value) End Function <Theory> <InlineData("class C { [|string|] s; }")> <InlineData("class C { void M() { [|M|](); } }")> <InlineData("class C { void M(string s) { M([|s|]); } }")> <InlineData("class C { void M(string s) { string local = """"; M([|local|]); } }")> <InlineData("using [|S|] = System.String;")> <InlineData("class C { [|global|]::System.String s; }")> <InlineData(" class C { /// <see cref=""C.[|M|]()"" /> void M() { } }")> Public Async Function TestReference(code As String) As Task Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync( TestWorkspace.CreateWorkspace( <Workspace> <Project Language="C#" AssemblyName=<%= TestProjectAssemblyName %> FilePath="Z:\TestProject.csproj" CommonReferences="true"> <Document Name="A.cs" FilePath="Z:\A.cs"> <%= code %> </Document> </Project> </Workspace>)) Dim rangeVertex = Await lsif.GetSelectedRangeAsync() Dim resultSetVertex = lsif.GetLinkedVertices(Of Graph.ResultSet)(rangeVertex, "next").Single() Dim hoverVertex = lsif.GetLinkedVertices(Of Graph.HoverResult)(resultSetVertex, Methods.TextDocumentHoverName).SingleOrDefault() Dim hoverMarkupContent = DirectCast(hoverVertex.Result.Contents.Value, MarkupContent) Dim expectedHoverContents As String Select Case code Case "class C { [|string|] s; }" expectedHoverContents = "class System.String" Case "class C { void M() { [|M|](); } }" expectedHoverContents = "void C.M()" Case "class C { void M(string s) { M([|s|]); } }" expectedHoverContents = $"({FeaturesResources.parameter}) string s" Case "class C { void M(string s) { string local = """"; M([|local|]); } }" expectedHoverContents = $"({FeaturesResources.local_variable}) string local" Case "using [|S|] = System.String;" expectedHoverContents = "class System.String" Case "class C { [|global|]::System.String s; }" expectedHoverContents = "<global namespace>" Case " class C { /// <see cref=""C.[|M|]()"" /> void M() { } }" expectedHoverContents = "void C.M()" Case Else Throw TestExceptionUtilities.UnexpectedValue(code) End Select Assert.Equal(MarkupKind.PlainText, hoverMarkupContent.Kind) Assert.Equal(expectedHoverContents + Environment.NewLine, hoverMarkupContent.Value) End Function <Fact> Public Async Function ToplevelResultsInMultipleFiles() As Task Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync( TestWorkspace.CreateWorkspace( <Workspace> <Project Language="C#" AssemblyName=<%= TestProjectAssemblyName %> FilePath="Z:\TestProject.csproj" CommonReferences="true"> <Document Name="A.cs" FilePath="Z:\A.cs"> class A { [|string|] s; } </Document> <Document Name="B.cs" FilePath="Z:\B.cs"> class B { [|string|] s; } </Document> <Document Name="C.cs" FilePath="Z:\C.cs"> class C { [|string|] s; } </Document> <Document Name="D.cs" FilePath="Z:\D.cs"> class D { [|string|] s; } </Document> <Document Name="E.cs" FilePath="Z:\E.cs"> class E { [|string|] s; } </Document> </Project> </Workspace>)) Dim hoverVertex As Graph.HoverResult = Nothing For Each rangeVertex In Await lsif.GetSelectedRangesAsync() Dim resultSetVertex = lsif.GetLinkedVertices(Of Graph.ResultSet)(rangeVertex, "next").Single() Dim vertex = lsif.GetLinkedVertices(Of Graph.HoverResult)(resultSetVertex, Methods.TextDocumentHoverName).Single() If hoverVertex Is Nothing Then hoverVertex = vertex Else Assert.Same(hoverVertex, vertex) End If Next Dim hoverMarkupContent = DirectCast(hoverVertex.Result.Contents.Value, MarkupContent) Assert.Equal(MarkupKind.PlainText, hoverMarkupContent.Kind) Assert.Equal("class System.String" + Environment.NewLine, hoverMarkupContent.Value) End Function End Class End Namespace
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/Remote/RemoteArguments.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { #region FindReferences [DataContract] internal sealed class SerializableSymbolAndProjectId : IEquatable<SerializableSymbolAndProjectId> { [DataMember(Order = 0)] public readonly string SymbolKeyData; [DataMember(Order = 1)] public readonly ProjectId ProjectId; public SerializableSymbolAndProjectId(string symbolKeyData, ProjectId projectId) { SymbolKeyData = symbolKeyData; ProjectId = projectId; } public override bool Equals(object obj) => Equals(obj as SerializableSymbolAndProjectId); public bool Equals(SerializableSymbolAndProjectId other) { if (this == other) return true; return this.ProjectId == other?.ProjectId && this.SymbolKeyData == other?.SymbolKeyData; } public override int GetHashCode() => Hash.Combine(this.SymbolKeyData, this.ProjectId.GetHashCode()); public static SerializableSymbolAndProjectId Dehydrate( IAliasSymbol alias, Document document, CancellationToken cancellationToken) { return alias == null ? null : Dehydrate(document.Project.Solution, alias, cancellationToken); } public static SerializableSymbolAndProjectId Dehydrate( Solution solution, ISymbol symbol, CancellationToken cancellationToken) { var project = solution.GetOriginatingProject(symbol); Contract.ThrowIfNull(project, WorkspacesResources.Symbols_project_could_not_be_found_in_the_provided_solution); return Create(symbol, project, cancellationToken); } public static SerializableSymbolAndProjectId Create(ISymbol symbol, Project project, CancellationToken cancellationToken) => new(symbol.GetSymbolKey(cancellationToken).ToString(), project.Id); public static bool TryCreate( ISymbol symbol, Solution solution, CancellationToken cancellationToken, out SerializableSymbolAndProjectId result) { var project = solution.GetOriginatingProject(symbol); if (project == null) { result = null; return false; } return TryCreate(symbol, project, cancellationToken, out result); } public static bool TryCreate( ISymbol symbol, Project project, CancellationToken cancellationToken, out SerializableSymbolAndProjectId result) { if (!SymbolKey.CanCreate(symbol, cancellationToken)) { result = null; return false; } result = new SerializableSymbolAndProjectId(SymbolKey.CreateString(symbol, cancellationToken), project.Id); return true; } public async Task<ISymbol> TryRehydrateAsync( Solution solution, CancellationToken cancellationToken) { var projectId = ProjectId; var project = solution.GetProject(projectId); var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); // The server and client should both be talking about the same compilation. As such // locations in symbols are save to resolve as we rehydrate the SymbolKey. var symbol = SymbolKey.ResolveString( SymbolKeyData, compilation, out var failureReason, cancellationToken).GetAnySymbol(); if (symbol == null) { try { throw new InvalidOperationException( $"We should always be able to resolve a symbol back on the host side:\r\n{project.Name}\r\n{SymbolKeyData}\r\n{failureReason}"); } catch (Exception ex) when (FatalError.ReportAndCatch(ex)) { return null; } } return symbol; } } [DataContract] internal readonly struct SerializableReferenceLocation { [DataMember(Order = 0)] public readonly DocumentId Document; [DataMember(Order = 1)] public readonly SerializableSymbolAndProjectId Alias; [DataMember(Order = 2)] public readonly TextSpan Location; [DataMember(Order = 3)] public readonly bool IsImplicit; [DataMember(Order = 4)] public readonly SymbolUsageInfo SymbolUsageInfo; [DataMember(Order = 5)] public readonly ImmutableDictionary<string, string> AdditionalProperties; [DataMember(Order = 6)] public readonly CandidateReason CandidateReason; public SerializableReferenceLocation( DocumentId document, SerializableSymbolAndProjectId alias, TextSpan location, bool isImplicit, SymbolUsageInfo symbolUsageInfo, ImmutableDictionary<string, string> additionalProperties, CandidateReason candidateReason) { Document = document; Alias = alias; Location = location; IsImplicit = isImplicit; SymbolUsageInfo = symbolUsageInfo; AdditionalProperties = additionalProperties; CandidateReason = candidateReason; } public static SerializableReferenceLocation Dehydrate( ReferenceLocation referenceLocation, CancellationToken cancellationToken) { return new SerializableReferenceLocation( referenceLocation.Document.Id, SerializableSymbolAndProjectId.Dehydrate(referenceLocation.Alias, referenceLocation.Document, cancellationToken), referenceLocation.Location.SourceSpan, referenceLocation.IsImplicit, referenceLocation.SymbolUsageInfo, referenceLocation.AdditionalProperties, referenceLocation.CandidateReason); } public async Task<ReferenceLocation> RehydrateAsync( Solution solution, CancellationToken cancellationToken) { var document = await solution.GetDocumentAsync(this.Document, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var aliasSymbol = await RehydrateAliasAsync(solution, cancellationToken).ConfigureAwait(false); var additionalProperties = this.AdditionalProperties; return new ReferenceLocation( document, aliasSymbol, CodeAnalysis.Location.Create(syntaxTree, Location), isImplicit: IsImplicit, symbolUsageInfo: SymbolUsageInfo, additionalProperties: additionalProperties ?? ImmutableDictionary<string, string>.Empty, candidateReason: CandidateReason); } private async Task<IAliasSymbol> RehydrateAliasAsync( Solution solution, CancellationToken cancellationToken) { if (Alias == null) return null; var symbol = await Alias.TryRehydrateAsync(solution, cancellationToken).ConfigureAwait(false); return symbol as IAliasSymbol; } } [DataContract] internal class SerializableSymbolGroup : IEquatable<SerializableSymbolGroup> { [DataMember(Order = 0)] public readonly HashSet<SerializableSymbolAndProjectId> Symbols; private int _hashCode; public SerializableSymbolGroup(HashSet<SerializableSymbolAndProjectId> symbols) { Symbols = new HashSet<SerializableSymbolAndProjectId>(symbols); } public override bool Equals(object obj) => obj is SerializableSymbolGroup group && Equals(group); public bool Equals(SerializableSymbolGroup other) { if (this == other) return true; return other != null && this.Symbols.SetEquals(other.Symbols); } public override int GetHashCode() { if (_hashCode == 0) { var hashCode = 0; foreach (var symbol in Symbols) hashCode += symbol.SymbolKeyData.GetHashCode(); _hashCode = hashCode; } return _hashCode; } public static SerializableSymbolGroup Dehydrate(Solution solution, SymbolGroup group, CancellationToken cancellationToken) { return new SerializableSymbolGroup(new HashSet<SerializableSymbolAndProjectId>( group.Symbols.Select(s => SerializableSymbolAndProjectId.Dehydrate(solution, s, cancellationToken)))); } } #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { #region FindReferences [DataContract] internal sealed class SerializableSymbolAndProjectId : IEquatable<SerializableSymbolAndProjectId> { [DataMember(Order = 0)] public readonly string SymbolKeyData; [DataMember(Order = 1)] public readonly ProjectId ProjectId; public SerializableSymbolAndProjectId(string symbolKeyData, ProjectId projectId) { SymbolKeyData = symbolKeyData; ProjectId = projectId; } public override bool Equals(object obj) => Equals(obj as SerializableSymbolAndProjectId); public bool Equals(SerializableSymbolAndProjectId other) { if (this == other) return true; return this.ProjectId == other?.ProjectId && this.SymbolKeyData == other?.SymbolKeyData; } public override int GetHashCode() => Hash.Combine(this.SymbolKeyData, this.ProjectId.GetHashCode()); public static SerializableSymbolAndProjectId Dehydrate( IAliasSymbol alias, Document document, CancellationToken cancellationToken) { return alias == null ? null : Dehydrate(document.Project.Solution, alias, cancellationToken); } public static SerializableSymbolAndProjectId Dehydrate( Solution solution, ISymbol symbol, CancellationToken cancellationToken) { var project = solution.GetOriginatingProject(symbol); Contract.ThrowIfNull(project, WorkspacesResources.Symbols_project_could_not_be_found_in_the_provided_solution); return Create(symbol, project, cancellationToken); } public static SerializableSymbolAndProjectId Create(ISymbol symbol, Project project, CancellationToken cancellationToken) => new(symbol.GetSymbolKey(cancellationToken).ToString(), project.Id); public static bool TryCreate( ISymbol symbol, Solution solution, CancellationToken cancellationToken, out SerializableSymbolAndProjectId result) { var project = solution.GetOriginatingProject(symbol); if (project == null) { result = null; return false; } return TryCreate(symbol, project, cancellationToken, out result); } public static bool TryCreate( ISymbol symbol, Project project, CancellationToken cancellationToken, out SerializableSymbolAndProjectId result) { if (!SymbolKey.CanCreate(symbol, cancellationToken)) { result = null; return false; } result = new SerializableSymbolAndProjectId(SymbolKey.CreateString(symbol, cancellationToken), project.Id); return true; } public async Task<ISymbol> TryRehydrateAsync( Solution solution, CancellationToken cancellationToken) { var projectId = ProjectId; var project = solution.GetProject(projectId); var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); // The server and client should both be talking about the same compilation. As such // locations in symbols are save to resolve as we rehydrate the SymbolKey. var symbol = SymbolKey.ResolveString( SymbolKeyData, compilation, out var failureReason, cancellationToken).GetAnySymbol(); if (symbol == null) { try { throw new InvalidOperationException( $"We should always be able to resolve a symbol back on the host side:\r\n{project.Name}\r\n{SymbolKeyData}\r\n{failureReason}"); } catch (Exception ex) when (FatalError.ReportAndCatch(ex)) { return null; } } return symbol; } } [DataContract] internal readonly struct SerializableReferenceLocation { [DataMember(Order = 0)] public readonly DocumentId Document; [DataMember(Order = 1)] public readonly SerializableSymbolAndProjectId Alias; [DataMember(Order = 2)] public readonly TextSpan Location; [DataMember(Order = 3)] public readonly bool IsImplicit; [DataMember(Order = 4)] public readonly SymbolUsageInfo SymbolUsageInfo; [DataMember(Order = 5)] public readonly ImmutableDictionary<string, string> AdditionalProperties; [DataMember(Order = 6)] public readonly CandidateReason CandidateReason; public SerializableReferenceLocation( DocumentId document, SerializableSymbolAndProjectId alias, TextSpan location, bool isImplicit, SymbolUsageInfo symbolUsageInfo, ImmutableDictionary<string, string> additionalProperties, CandidateReason candidateReason) { Document = document; Alias = alias; Location = location; IsImplicit = isImplicit; SymbolUsageInfo = symbolUsageInfo; AdditionalProperties = additionalProperties; CandidateReason = candidateReason; } public static SerializableReferenceLocation Dehydrate( ReferenceLocation referenceLocation, CancellationToken cancellationToken) { return new SerializableReferenceLocation( referenceLocation.Document.Id, SerializableSymbolAndProjectId.Dehydrate(referenceLocation.Alias, referenceLocation.Document, cancellationToken), referenceLocation.Location.SourceSpan, referenceLocation.IsImplicit, referenceLocation.SymbolUsageInfo, referenceLocation.AdditionalProperties, referenceLocation.CandidateReason); } public async Task<ReferenceLocation> RehydrateAsync( Solution solution, CancellationToken cancellationToken) { var document = await solution.GetDocumentAsync(this.Document, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var aliasSymbol = await RehydrateAliasAsync(solution, cancellationToken).ConfigureAwait(false); var additionalProperties = this.AdditionalProperties; return new ReferenceLocation( document, aliasSymbol, CodeAnalysis.Location.Create(syntaxTree, Location), isImplicit: IsImplicit, symbolUsageInfo: SymbolUsageInfo, additionalProperties: additionalProperties ?? ImmutableDictionary<string, string>.Empty, candidateReason: CandidateReason); } private async Task<IAliasSymbol> RehydrateAliasAsync( Solution solution, CancellationToken cancellationToken) { if (Alias == null) return null; var symbol = await Alias.TryRehydrateAsync(solution, cancellationToken).ConfigureAwait(false); return symbol as IAliasSymbol; } } [DataContract] internal class SerializableSymbolGroup : IEquatable<SerializableSymbolGroup> { [DataMember(Order = 0)] public readonly HashSet<SerializableSymbolAndProjectId> Symbols; private int _hashCode; public SerializableSymbolGroup(HashSet<SerializableSymbolAndProjectId> symbols) { Symbols = new HashSet<SerializableSymbolAndProjectId>(symbols); } public override bool Equals(object obj) => obj is SerializableSymbolGroup group && Equals(group); public bool Equals(SerializableSymbolGroup other) { if (this == other) return true; return other != null && this.Symbols.SetEquals(other.Symbols); } public override int GetHashCode() { if (_hashCode == 0) { var hashCode = 0; foreach (var symbol in Symbols) hashCode += symbol.SymbolKeyData.GetHashCode(); _hashCode = hashCode; } return _hashCode; } public static SerializableSymbolGroup Dehydrate(Solution solution, SymbolGroup group, CancellationToken cancellationToken) { return new SerializableSymbolGroup(new HashSet<SerializableSymbolAndProjectId>( group.Symbols.Select(s => SerializableSymbolAndProjectId.Dehydrate(solution, s, cancellationToken)))); } } #endregion }
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IDynamicInvocationExpression.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.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IDynamicInvocationExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_DynamicArgument() { string source = @" class C { void M(C c, dynamic d) { /*<bind>*/c.M2(d)/*</bind>*/; } public void M2(int i) { } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(d)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(1): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_MultipleApplicableSymbols() { string source = @" class C { void M(C c, dynamic d) { var x = /*<bind>*/c.M2(d)/*</bind>*/; } public void M2(int i) { } public void M2(long i) { } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(d)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(1): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_MultipleArgumentsAndApplicableSymbols() { string source = @" class C { void M(C c, dynamic d) { char ch = 'c'; var x = /*<bind>*/c.M2(d, ch)/*</bind>*/; } public void M2(int i, char ch) { } public void M2(long i, char ch) { } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(d, ch)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(2): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ILocalReferenceOperation: ch (OperationKind.LocalReference, Type: System.Char) (Syntax: 'ch') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_ArgumentNames() { string source = @" class C { void M(C c, dynamic d, dynamic e) { var x = /*<bind>*/c.M2(i: d, ch: e)/*</bind>*/; } public void M2(int i, char ch) { } public void M2(long i, char ch) { } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(i: d, ch: e)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(2): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'e') ArgumentNames(2): ""i"" ""ch"" ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_ArgumentRefKinds() { string source = @" class C { void M(C c, object d, dynamic e) { int k; var x = /*<bind>*/c.M2(ref d, out k, e)/*</bind>*/; } public void M2(ref object i, out int j, char c) { j = 0; } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(ref d, out k, e)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(3): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'd') ILocalReferenceOperation: k (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'k') IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'e') ArgumentNames(0) ArgumentRefKinds(3): Ref Out None "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_DelegateInvocation() { string source = @" using System; class C { public Action<object> F; void M(dynamic i) { var x = /*<bind>*/F(i)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'F(i)') Expression: IFieldReferenceOperation: System.Action<System.Object> C.F (OperationKind.FieldReference, Type: System.Action<System.Object>) (Syntax: 'F') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'F') Arguments(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'i') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0649: Field 'C.F' is never assigned to, and will always have its default value null // public Action<object> F; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("C.F", "null").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_WithDynamicReceiver() { string source = @" class C { void M(dynamic d, int i) { var x = /*<bind>*/d(i)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'd(i)') Expression: IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') Arguments(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_WithDynamicMemberReceiver() { string source = @" class C { void M(dynamic c, int i) { var x = /*<bind>*/c.M2(i)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(i)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: dynamic) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'c') Arguments(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_WithDynamicTypedMemberReceiver() { string source = @" class C { dynamic M2 = null; void M(C c, int i) { var x = /*<bind>*/c.M2(i)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(i)') Expression: IFieldReferenceOperation: dynamic C.M2 (OperationKind.FieldReference, Type: dynamic) (Syntax: 'c.M2') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_AllFields() { string source = @" class C { void M(C c, dynamic d) { int i = 0; var x = /*<bind>*/c.M2(ref i, c: d)/*</bind>*/; } public void M2(ref int i, char c) { } public void M2(ref int i, long c) { } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(ref i, c: d)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(2): ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(2): ""null"" ""c"" ArgumentRefKinds(2): Ref None "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_ErrorBadDynamicMethodArgLambda() { string source = @" using System; class C { public void M(C c) { dynamic y = null; var x = /*<bind>*/c.M2(delegate { }, y)/*</bind>*/; } public void M2(Action a, Action y) { } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic, IsInvalid) (Syntax: 'c.M2(delegate { }, y)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(2): IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'delegate { }') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ }') IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '{ }') ReturnedValue: null ILocalReferenceOperation: y (OperationKind.LocalReference, Type: dynamic) (Syntax: 'y') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. // var x = /*<bind>*/c.M2(delegate { }, y)/*</bind>*/; Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "delegate { }").WithLocation(9, 32) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_OverloadResolutionFailure() { string source = @" class C { void M(C c, dynamic d) { var x = /*<bind>*/c.M2(d)/*</bind>*/; } public void M2() { } public void M2(int i, int j) { } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'c.M2(d)') Children(2): IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'c') IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic, IsInvalid) (Syntax: 'd') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS7036: There is no argument given that corresponds to the required formal parameter 'j' of 'C.M2(int, int)' // var x = /*<bind>*/c.M2(d)/*</bind>*/; Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M2").WithArguments("j", "C.M2(int, int)").WithLocation(6, 29), // CS0815: Cannot assign void to an implicitly-typed variable // var x = /*<bind>*/c.M2(d)/*</bind>*/; Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "x = /*<bind>*/c.M2(d)").WithArguments("void").WithLocation(6, 13) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_InConstructorInitializer() { string source = @" class B { protected B(int x) { } } class C : B { C(dynamic x) : base((int)/*<bind>*/Goo(x)/*</bind>*/) { } static object Goo(object x) { return x; } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'Goo(x)') Expression: IDynamicMemberReferenceOperation (Member Name: ""Goo"", Containing Type: C) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'Goo') Type Arguments(0) Instance Receiver: null Arguments(1): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'x') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_NoControlFlow() { string source = @" class C { void M(C c, dynamic d) /*<bind>*/{ c.M2(d); }/*</bind>*/ public void M2(int i) { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c.M2(d);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(d)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(1): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowNullReceiver() { // Also tests non-zero TypeArguments and non-null ContainingType for IDynamicMemberReferenceOperation string source = @" class C { void M(dynamic d1, dynamic d2) /*<bind>*/{ C.M2<int>(d1 ?? d2); }/*</bind>*/ public static void M2<T>(int i) { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Next (Regular) Block[B4] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'C.M2<int>(d1 ?? d2);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'C.M2<int>(d1 ?? d2)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: C) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'C.M2<int>') Type Arguments(1): Symbol: System.Int32 Instance Receiver: null Arguments(1): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1 ?? d2') ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowInReceiver() { string source = @" class C { void M(C c1, C c2, dynamic d) /*<bind>*/{ (c1 ?? c2).M2(d); }/*</bind>*/ public void M2(int i) { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(c1 ?? c2).M2(d);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: '(c1 ?? c2).M2(d)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: '(c1 ?? c2).M2') Type Arguments(0) Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1 ?? c2') Arguments(1): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowInReceiverEmptyArgList() { string source = @" class C { void M(dynamic d1, dynamic d2) /*<bind>*/{ (d1 ?? d2).M2(); }/*</bind>*/ public void M2() { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Next (Regular) Block[B4] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(d1 ?? d2).M2();') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: '(d1 ?? d2).M2()') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: dynamic) (Syntax: '(d1 ?? d2).M2') Type Arguments(0) Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1 ?? d2') Arguments(0) ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowInFirstArgument() { string source = @" class C { void M(char ch, C c, dynamic d1, dynamic d2) /*<bind>*/{ c.M2(d1 ?? d2, ch); }/*</bind>*/ public void M2(int i, char ch) { } public void M2(long i, char ch) { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c.M2(d1 ?? d2, ch);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(d1 ?? d2, ch)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c') Arguments(2): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1 ?? d2') IParameterReferenceOperation: ch (OperationKind.ParameterReference, Type: System.Char) (Syntax: 'ch') ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowInSecondArgument() { string source = @" class C { void M(C c, dynamic d1, char? ch1, char ch2) /*<bind>*/{ c.M2(d1, ch1 ?? ch2); }/*</bind>*/ public void M2(int i, char ch) { } public void M2(long i, char ch) { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [3] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd1') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'ch1') Value: IParameterReferenceOperation: ch1 (OperationKind.ParameterReference, Type: System.Char?) (Syntax: 'ch1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'ch1') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Char?, IsImplicit) (Syntax: 'ch1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'ch1') Value: IInvocationOperation ( System.Char System.Char?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Char, IsImplicit) (Syntax: 'ch1') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Char?, IsImplicit) (Syntax: 'ch1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'ch2') Value: IParameterReferenceOperation: ch2 (OperationKind.ParameterReference, Type: System.Char) (Syntax: 'ch2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c.M2(d1, ch1 ?? ch2);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(d1, ch1 ?? ch2)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c') Arguments(2): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Char, IsImplicit) (Syntax: 'ch1 ?? ch2') ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowInMultipleArguments() { string source = @" class C { void M(bool flag, char ch1, char ch2, C c, dynamic d1, dynamic d2) /*<bind>*/{ c.M2(d1 ?? d2, flag ? ch1 : ch2); }/*</bind>*/ public void M2(int i, char ch) { } public void M2(long i, char ch) { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] [3] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Jump if False (Regular) to Block[B7] IParameterReferenceOperation: flag (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'flag') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'ch1') Value: IParameterReferenceOperation: ch1 (OperationKind.ParameterReference, Type: System.Char) (Syntax: 'ch1') Next (Regular) Block[B8] Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'ch2') Value: IParameterReferenceOperation: ch2 (OperationKind.ParameterReference, Type: System.Char) (Syntax: 'ch2') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c.M2(d1 ?? ... ch1 : ch2);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(d1 ?? ... ch1 : ch2)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c') Arguments(2): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1 ?? d2') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Char, IsImplicit) (Syntax: 'flag ? ch1 : ch2') ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowInReceiverAndArgument() { // Control flow in receiver and argument. // Also includes use of argument names and RefKinds. string source = @" class C { void M(C c1, C c2, dynamic d1, dynamic d2, int i) /*<bind>*/{ (c1 ?? c2).M2(ref i, c: d1 ?? d2); }/*</bind>*/ public void M2(ref int i, char c) { } public void M2(ref int i, long c) { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] [2] [4] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B5] Entering: {R3} .locals {R3} { CaptureIds: [3] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd1') Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Leaving: {R3} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Next (Regular) Block[B8] Leaving: {R3} } Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd2') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(c1 ?? c2). ... d1 ?? d2);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: '(c1 ?? c2). ... : d1 ?? d2)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: '(c1 ?? c2).M2') Type Arguments(0) Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1 ?? c2') Arguments(2): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1 ?? d2') ArgumentNames(2): ""null"" ""c"" ArgumentRefKinds(2): Ref None Next (Regular) Block[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowWithDynamicTypedMemberReceiver() { string source = @" class C { dynamic M2 = null; void M(C c, int? i1, int i2) /*<bind>*/{ c.M2(i1 ?? i2); }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c.M2') Value: IFieldReferenceOperation: dynamic C.M2 (OperationKind.FieldReference, Type: dynamic) (Syntax: 'c.M2') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1') Value: IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i1') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2') Value: IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c.M2(i1 ?? i2);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(i1 ?? i2)') Expression: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'c.M2') Arguments(1): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i1 ?? i2') ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } } }
// Licensed to the .NET Foundation under one or more 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.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_IDynamicInvocationExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_DynamicArgument() { string source = @" class C { void M(C c, dynamic d) { /*<bind>*/c.M2(d)/*</bind>*/; } public void M2(int i) { } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(d)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(1): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_MultipleApplicableSymbols() { string source = @" class C { void M(C c, dynamic d) { var x = /*<bind>*/c.M2(d)/*</bind>*/; } public void M2(int i) { } public void M2(long i) { } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(d)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(1): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_MultipleArgumentsAndApplicableSymbols() { string source = @" class C { void M(C c, dynamic d) { char ch = 'c'; var x = /*<bind>*/c.M2(d, ch)/*</bind>*/; } public void M2(int i, char ch) { } public void M2(long i, char ch) { } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(d, ch)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(2): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ILocalReferenceOperation: ch (OperationKind.LocalReference, Type: System.Char) (Syntax: 'ch') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_ArgumentNames() { string source = @" class C { void M(C c, dynamic d, dynamic e) { var x = /*<bind>*/c.M2(i: d, ch: e)/*</bind>*/; } public void M2(int i, char ch) { } public void M2(long i, char ch) { } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(i: d, ch: e)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(2): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'e') ArgumentNames(2): ""i"" ""ch"" ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_ArgumentRefKinds() { string source = @" class C { void M(C c, object d, dynamic e) { int k; var x = /*<bind>*/c.M2(ref d, out k, e)/*</bind>*/; } public void M2(ref object i, out int j, char c) { j = 0; } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(ref d, out k, e)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(3): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Object) (Syntax: 'd') ILocalReferenceOperation: k (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'k') IParameterReferenceOperation: e (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'e') ArgumentNames(0) ArgumentRefKinds(3): Ref Out None "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_DelegateInvocation() { string source = @" using System; class C { public Action<object> F; void M(dynamic i) { var x = /*<bind>*/F(i)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'F(i)') Expression: IFieldReferenceOperation: System.Action<System.Object> C.F (OperationKind.FieldReference, Type: System.Action<System.Object>) (Syntax: 'F') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'F') Arguments(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'i') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0649: Field 'C.F' is never assigned to, and will always have its default value null // public Action<object> F; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("C.F", "null").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_WithDynamicReceiver() { string source = @" class C { void M(dynamic d, int i) { var x = /*<bind>*/d(i)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'd(i)') Expression: IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') Arguments(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_WithDynamicMemberReceiver() { string source = @" class C { void M(dynamic c, int i) { var x = /*<bind>*/c.M2(i)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(i)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: dynamic) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'c') Arguments(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_WithDynamicTypedMemberReceiver() { string source = @" class C { dynamic M2 = null; void M(C c, int i) { var x = /*<bind>*/c.M2(i)/*</bind>*/; } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(i)') Expression: IFieldReferenceOperation: dynamic C.M2 (OperationKind.FieldReference, Type: dynamic) (Syntax: 'c.M2') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(1): IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_AllFields() { string source = @" class C { void M(C c, dynamic d) { int i = 0; var x = /*<bind>*/c.M2(ref i, c: d)/*</bind>*/; } public void M2(ref int i, char c) { } public void M2(ref int i, long c) { } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(ref i, c: d)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(2): ILocalReferenceOperation: i (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i') IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(2): ""null"" ""c"" ArgumentRefKinds(2): Ref None "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_ErrorBadDynamicMethodArgLambda() { string source = @" using System; class C { public void M(C c) { dynamic y = null; var x = /*<bind>*/c.M2(delegate { }, y)/*</bind>*/; } public void M2(Action a, Action y) { } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic, IsInvalid) (Syntax: 'c.M2(delegate { }, y)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(2): IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'delegate { }') IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ }') IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '{ }') ReturnedValue: null ILocalReferenceOperation: y (OperationKind.LocalReference, Type: dynamic) (Syntax: 'y') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = new DiagnosticDescription[] { // CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. // var x = /*<bind>*/c.M2(delegate { }, y)/*</bind>*/; Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "delegate { }").WithLocation(9, 32) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_OverloadResolutionFailure() { string source = @" class C { void M(C c, dynamic d) { var x = /*<bind>*/c.M2(d)/*</bind>*/; } public void M2() { } public void M2(int i, int j) { } } "; string expectedOperationTree = @" IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'c.M2(d)') Children(2): IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'c') IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic, IsInvalid) (Syntax: 'd') "; var expectedDiagnostics = new DiagnosticDescription[] { // CS7036: There is no argument given that corresponds to the required formal parameter 'j' of 'C.M2(int, int)' // var x = /*<bind>*/c.M2(d)/*</bind>*/; Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M2").WithArguments("j", "C.M2(int, int)").WithLocation(6, 29), // CS0815: Cannot assign void to an implicitly-typed variable // var x = /*<bind>*/c.M2(d)/*</bind>*/; Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, "x = /*<bind>*/c.M2(d)").WithArguments("void").WithLocation(6, 13) }; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void DynamicInvocation_InConstructorInitializer() { string source = @" class B { protected B(int x) { } } class C : B { C(dynamic x) : base((int)/*<bind>*/Goo(x)/*</bind>*/) { } static object Goo(object x) { return x; } } "; string expectedOperationTree = @" IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'Goo(x)') Expression: IDynamicMemberReferenceOperation (Member Name: ""Goo"", Containing Type: C) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'Goo') Type Arguments(0) Instance Receiver: null Arguments(1): IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'x') ArgumentNames(0) ArgumentRefKinds(0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_NoControlFlow() { string source = @" class C { void M(C c, dynamic d) /*<bind>*/{ c.M2(d); }/*</bind>*/ public void M2(int i) { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c.M2(d);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(d)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(1): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowNullReceiver() { // Also tests non-zero TypeArguments and non-null ContainingType for IDynamicMemberReferenceOperation string source = @" class C { void M(dynamic d1, dynamic d2) /*<bind>*/{ C.M2<int>(d1 ?? d2); }/*</bind>*/ public static void M2<T>(int i) { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Next (Regular) Block[B4] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'C.M2<int>(d1 ?? d2);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'C.M2<int>(d1 ?? d2)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: C) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'C.M2<int>') Type Arguments(1): Symbol: System.Int32 Instance Receiver: null Arguments(1): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1 ?? d2') ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowInReceiver() { string source = @" class C { void M(C c1, C c2, dynamic d) /*<bind>*/{ (c1 ?? c2).M2(d); }/*</bind>*/ public void M2(int i) { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(c1 ?? c2).M2(d);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: '(c1 ?? c2).M2(d)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: '(c1 ?? c2).M2') Type Arguments(0) Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1 ?? c2') Arguments(1): IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd') ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowInReceiverEmptyArgList() { string source = @" class C { void M(dynamic d1, dynamic d2) /*<bind>*/{ (d1 ?? d2).M2(); }/*</bind>*/ public void M2() { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Next (Regular) Block[B4] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(d1 ?? d2).M2();') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: '(d1 ?? d2).M2()') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: dynamic) (Syntax: '(d1 ?? d2).M2') Type Arguments(0) Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1 ?? d2') Arguments(0) ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B5] Leaving: {R1} } Block[B5] - Exit Predecessors: [B4] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowInFirstArgument() { string source = @" class C { void M(char ch, C c, dynamic d1, dynamic d2) /*<bind>*/{ c.M2(d1 ?? d2, ch); }/*</bind>*/ public void M2(int i, char ch) { } public void M2(long i, char ch) { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c.M2(d1 ?? d2, ch);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(d1 ?? d2, ch)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c') Arguments(2): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1 ?? d2') IParameterReferenceOperation: ch (OperationKind.ParameterReference, Type: System.Char) (Syntax: 'ch') ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowInSecondArgument() { string source = @" class C { void M(C c, dynamic d1, char? ch1, char ch2) /*<bind>*/{ c.M2(d1, ch1 ?? ch2); }/*</bind>*/ public void M2(int i, char ch) { } public void M2(long i, char ch) { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [3] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd1') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'ch1') Value: IParameterReferenceOperation: ch1 (OperationKind.ParameterReference, Type: System.Char?) (Syntax: 'ch1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'ch1') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Char?, IsImplicit) (Syntax: 'ch1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'ch1') Value: IInvocationOperation ( System.Char System.Char?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Char, IsImplicit) (Syntax: 'ch1') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Char?, IsImplicit) (Syntax: 'ch1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'ch2') Value: IParameterReferenceOperation: ch2 (OperationKind.ParameterReference, Type: System.Char) (Syntax: 'ch2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c.M2(d1, ch1 ?? ch2);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(d1, ch1 ?? ch2)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c') Arguments(2): IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Char, IsImplicit) (Syntax: 'ch1 ?? ch2') ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowInMultipleArguments() { string source = @" class C { void M(bool flag, char ch1, char ch2, C c, dynamic d1, dynamic d2) /*<bind>*/{ c.M2(d1 ?? d2, flag ? ch1 : ch2); }/*</bind>*/ public void M2(int i, char ch) { } public void M2(long i, char ch) { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] [3] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Jump if False (Regular) to Block[B7] IParameterReferenceOperation: flag (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'flag') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'ch1') Value: IParameterReferenceOperation: ch1 (OperationKind.ParameterReference, Type: System.Char) (Syntax: 'ch1') Next (Regular) Block[B8] Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'ch2') Value: IParameterReferenceOperation: ch2 (OperationKind.ParameterReference, Type: System.Char) (Syntax: 'ch2') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c.M2(d1 ?? ... ch1 : ch2);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(d1 ?? ... ch1 : ch2)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: 'c.M2') Type Arguments(0) Instance Receiver: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c') Arguments(2): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1 ?? d2') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Char, IsImplicit) (Syntax: 'flag ? ch1 : ch2') ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowInReceiverAndArgument() { // Control flow in receiver and argument. // Also includes use of argument names and RefKinds. string source = @" class C { void M(C c1, C c2, dynamic d1, dynamic d2, int i) /*<bind>*/{ (c1 ?? c2).M2(ref i, c: d1 ?? d2); }/*</bind>*/ public void M2(ref int i, char c) { } public void M2(ref int i, long c) { } } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [1] [2] [4] .locals {R2} { CaptureIds: [0] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R2} Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Leaving: {R2} } Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i') Value: IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') Next (Regular) Block[B5] Entering: {R3} .locals {R3} { CaptureIds: [3] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IParameterReferenceOperation: d1 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd1') Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'd1') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Leaving: {R3} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd1') Value: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1') Next (Regular) Block[B8] Leaving: {R3} } Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'd2') Value: IParameterReferenceOperation: d2 (OperationKind.ParameterReference, Type: dynamic) (Syntax: 'd2') Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B6] [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(c1 ?? c2). ... d1 ?? d2);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: '(c1 ?? c2). ... : d1 ?? d2)') Expression: IDynamicMemberReferenceOperation (Member Name: ""M2"", Containing Type: null) (OperationKind.DynamicMemberReference, Type: null) (Syntax: '(c1 ?? c2).M2') Type Arguments(0) Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1 ?? c2') Arguments(2): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'd1 ?? d2') ArgumentNames(2): ""null"" ""c"" ArgumentRefKinds(2): Ref None Next (Regular) Block[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void DynamicInvocation_ControlFlowWithDynamicTypedMemberReceiver() { string source = @" class C { dynamic M2 = null; void M(C c, int? i1, int i2) /*<bind>*/{ c.M2(i1 ?? i2); }/*</bind>*/ } "; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c.M2') Value: IFieldReferenceOperation: dynamic C.M2 (OperationKind.FieldReference, Type: dynamic) (Syntax: 'c.M2') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1') Value: IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1') Value: IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i1') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2') Value: IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c.M2(i1 ?? i2);') Expression: IDynamicInvocationOperation (OperationKind.DynamicInvocation, Type: dynamic) (Syntax: 'c.M2(i1 ?? i2)') Expression: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: dynamic, IsImplicit) (Syntax: 'c.M2') Arguments(1): IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i1 ?? i2') ArgumentNames(0) ArgumentRefKinds(0) Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; var expectedDiagnostics = DiagnosticDescription.None; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } } }
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Tools/Source/RunTests/FileUtil.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; namespace RunTests { internal static class FileUtil { /// <summary> /// Ensure a directory with the given name is present. Will be created if necessary. True /// is returned when it is created. /// </summary> internal static bool EnsureDirectory(string directory) { if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); return true; } return false; } /// <summary> /// Delete file if it exists and swallow any potential exceptions. Returns true if the /// file is actually deleted. /// </summary> internal static bool DeleteFile(string filePath) { try { if (File.Exists(filePath)) { File.Delete(filePath); return true; } } catch { // Ignore } return false; } /// <summary> /// Delete directory if it exists and swallow any potential exceptions. Returns true if the /// directory is actually deleted. /// </summary> internal static bool DeleteDirectory(string directory) { try { if (Directory.Exists(directory)) { Directory.Delete(directory, recursive: true); return true; } } catch { // Ignore } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; namespace RunTests { internal static class FileUtil { /// <summary> /// Ensure a directory with the given name is present. Will be created if necessary. True /// is returned when it is created. /// </summary> internal static bool EnsureDirectory(string directory) { if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); return true; } return false; } /// <summary> /// Delete file if it exists and swallow any potential exceptions. Returns true if the /// file is actually deleted. /// </summary> internal static bool DeleteFile(string filePath) { try { if (File.Exists(filePath)) { File.Delete(filePath); return true; } } catch { // Ignore } return false; } /// <summary> /// Delete directory if it exists and swallow any potential exceptions. Returns true if the /// directory is actually deleted. /// </summary> internal static bool DeleteDirectory(string directory) { try { if (Directory.Exists(directory)) { Directory.Delete(directory, recursive: true); return true; } } catch { // Ignore } return false; } } }
-1
dotnet/roslyn
55,022
Fix 'sync namespace' with file scoped namespaces
Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:13:03Z
2021-07-26T19:25:07Z
1453f20221fbd626b5195bf0c8653078e53f292e
5e956729df67fdd6610253b05e1a232fe595af73
Fix 'sync namespace' with file scoped namespaces. Fixes #54749 Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Analyzers/Core/CodeFixes/NewLines/MultipleBlankLines/AbstractMultipleBlankLinesCodeFixProvider.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.NewLines.MultipleBlankLines { [ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeFixProviderNames.RemoveBlankLines), Shared] internal class MultipleBlankLinesCodeFixProvider : CodeFixProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public MultipleBlankLinesCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.MultipleBlankLinesDiagnosticId); public override Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostic = context.Diagnostics.First(); context.RegisterCodeFix(new MyCodeAction( c => UpdateDocumentAsync(document, diagnostic, c)), context.Diagnostics); return Task.CompletedTask; } private static Task<Document> UpdateDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken) => FixAllAsync(document, ImmutableArray.Create(diagnostic), cancellationToken); private static async Task<Document> FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken) { var syntaxKinds = document.GetRequiredLanguageService<ISyntaxKindsService>(); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); using var _ = PooledDictionary<SyntaxToken, SyntaxToken>.GetInstance(out var replacements); foreach (var diagnostic in diagnostics) { var token = root.FindToken(diagnostic.AdditionalLocations[0].SourceSpan.Start); var leadingTrivia = UpdateLeadingTrivia(syntaxKinds, token.LeadingTrivia); replacements.Add(token, token.WithLeadingTrivia(leadingTrivia)); } var newRoot = root.ReplaceTokens(replacements.Keys, (token, _) => replacements[token]); return document.WithSyntaxRoot(newRoot); } private static SyntaxTriviaList UpdateLeadingTrivia(ISyntaxKindsService syntaxKinds, SyntaxTriviaList triviaList) { using var _ = ArrayBuilder<SyntaxTrivia>.GetInstance(out var builder); var currentStart = 0; while (currentStart < triviaList.Count) { var trivia = triviaList[currentStart]; builder.Add(trivia); // If it's not an end of line, just keep going. if (trivia.RawKind != syntaxKinds.EndOfLineTrivia) { currentStart++; continue; } // We have a newlines. Walk forward to get to the last newline in this sequence. var currentEnd = currentStart + 1; while (currentEnd < triviaList.Count && IsEndOfLine(syntaxKinds, triviaList, currentEnd)) { currentEnd++; } var newLineCount = currentEnd - currentStart; if (newLineCount == 1) { // only a single newline. keep as is. currentStart = currentEnd; continue; } // we have two or more newlines. We have three cases to handle: // // 1. We're at the start of the token's trivia. Collapse this down to 1 blank line. // 2. We follow structured trivia (i.e. pp-directive or doc comment). These already end with a newline, // so we only need to add one newline to get a blank line. // 3. We follow something else. We only want to collapse if we have 3 or more newlines. if (currentStart == 0) { // case 1. // skip the second newline onwards. currentStart = currentEnd; continue; } if (triviaList[currentStart - 1].HasStructure) { // case 2. // skip the second newline onwards currentStart = currentEnd; continue; } if (newLineCount >= 3) { // case 3. We want to keep the first two newlines to end up with one blank line, // and then skip the rest. builder.Add(triviaList[currentStart + 1]); currentStart = currentEnd; continue; } // for anything else just add the trivia and move forward like normal. currentStart++; } return new SyntaxTriviaList(builder.ToImmutable()); } private static bool IsEndOfLine(ISyntaxKindsService syntaxKinds, SyntaxTriviaList triviaList, int index) { if (index >= triviaList.Count) return false; var trivia = triviaList[index]; return trivia.RawKind == syntaxKinds.EndOfLineTrivia; } public override FixAllProvider? GetFixAllProvider() => FixAllProvider.Create(async (context, document, diagnostics) => await FixAllAsync(document, diagnostics, context.CancellationToken).ConfigureAwait(false)); private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CodeFixesResources.Remove_extra_blank_lines, createChangedDocument, CodeFixesResources.Remove_extra_blank_lines) { } } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.NewLines.MultipleBlankLines { [ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeFixProviderNames.RemoveBlankLines), Shared] internal class MultipleBlankLinesCodeFixProvider : CodeFixProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public MultipleBlankLinesCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.MultipleBlankLinesDiagnosticId); public override Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostic = context.Diagnostics.First(); context.RegisterCodeFix(new MyCodeAction( c => UpdateDocumentAsync(document, diagnostic, c)), context.Diagnostics); return Task.CompletedTask; } private static Task<Document> UpdateDocumentAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken) => FixAllAsync(document, ImmutableArray.Create(diagnostic), cancellationToken); private static async Task<Document> FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken) { var syntaxKinds = document.GetRequiredLanguageService<ISyntaxKindsService>(); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); using var _ = PooledDictionary<SyntaxToken, SyntaxToken>.GetInstance(out var replacements); foreach (var diagnostic in diagnostics) { var token = root.FindToken(diagnostic.AdditionalLocations[0].SourceSpan.Start); var leadingTrivia = UpdateLeadingTrivia(syntaxKinds, token.LeadingTrivia); replacements.Add(token, token.WithLeadingTrivia(leadingTrivia)); } var newRoot = root.ReplaceTokens(replacements.Keys, (token, _) => replacements[token]); return document.WithSyntaxRoot(newRoot); } private static SyntaxTriviaList UpdateLeadingTrivia(ISyntaxKindsService syntaxKinds, SyntaxTriviaList triviaList) { using var _ = ArrayBuilder<SyntaxTrivia>.GetInstance(out var builder); var currentStart = 0; while (currentStart < triviaList.Count) { var trivia = triviaList[currentStart]; builder.Add(trivia); // If it's not an end of line, just keep going. if (trivia.RawKind != syntaxKinds.EndOfLineTrivia) { currentStart++; continue; } // We have a newlines. Walk forward to get to the last newline in this sequence. var currentEnd = currentStart + 1; while (currentEnd < triviaList.Count && IsEndOfLine(syntaxKinds, triviaList, currentEnd)) { currentEnd++; } var newLineCount = currentEnd - currentStart; if (newLineCount == 1) { // only a single newline. keep as is. currentStart = currentEnd; continue; } // we have two or more newlines. We have three cases to handle: // // 1. We're at the start of the token's trivia. Collapse this down to 1 blank line. // 2. We follow structured trivia (i.e. pp-directive or doc comment). These already end with a newline, // so we only need to add one newline to get a blank line. // 3. We follow something else. We only want to collapse if we have 3 or more newlines. if (currentStart == 0) { // case 1. // skip the second newline onwards. currentStart = currentEnd; continue; } if (triviaList[currentStart - 1].HasStructure) { // case 2. // skip the second newline onwards currentStart = currentEnd; continue; } if (newLineCount >= 3) { // case 3. We want to keep the first two newlines to end up with one blank line, // and then skip the rest. builder.Add(triviaList[currentStart + 1]); currentStart = currentEnd; continue; } // for anything else just add the trivia and move forward like normal. currentStart++; } return new SyntaxTriviaList(builder.ToImmutable()); } private static bool IsEndOfLine(ISyntaxKindsService syntaxKinds, SyntaxTriviaList triviaList, int index) { if (index >= triviaList.Count) return false; var trivia = triviaList[index]; return trivia.RawKind == syntaxKinds.EndOfLineTrivia; } public override FixAllProvider? GetFixAllProvider() => FixAllProvider.Create(async (context, document, diagnostics) => await FixAllAsync(document, diagnostics, context.CancellationToken).ConfigureAwait(false)); private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CodeFixesResources.Remove_extra_blank_lines, createChangedDocument, CodeFixesResources.Remove_extra_blank_lines) { } } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Analyzers/CSharp/Analyzers/MatchFolderAndNamespace/CSharpMatchFolderAndNamespaceDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Analyzers.MatchFolderAndNamespace; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp.Analyzers.MatchFolderAndNamespace { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpMatchFolderAndNamespaceDiagnosticAnalyzer : AbstractMatchFolderAndNamespaceDiagnosticAnalyzer<SyntaxKind, BaseNamespaceDeclarationSyntax> { protected override ISyntaxFacts GetSyntaxFacts() => CSharpSyntaxFacts.Instance; protected override ImmutableArray<SyntaxKind> GetSyntaxKindsToAnalyze() => ImmutableArray.Create(SyntaxKind.NamespaceDeclaration, SyntaxKind.FileScopedNamespaceDeclaration); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Analyzers.MatchFolderAndNamespace; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp.Analyzers.MatchFolderAndNamespace { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpMatchFolderAndNamespaceDiagnosticAnalyzer : AbstractMatchFolderAndNamespaceDiagnosticAnalyzer<SyntaxKind, BaseNamespaceDeclarationSyntax> { protected override ISyntaxFacts GetSyntaxFacts() => CSharpSyntaxFacts.Instance; protected override ImmutableArray<SyntaxKind> GetSyntaxKindsToAnalyze() => ImmutableArray.Create(SyntaxKind.NamespaceDeclaration, SyntaxKind.FileScopedNamespaceDeclaration); } }
1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Analyzers/CSharp/Tests/MatchFolderAndNamespace/CSharpMatchFolderAndNamespaceTests.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.Threading.Tasks; using Xunit; using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier< Microsoft.CodeAnalysis.CSharp.Analyzers.MatchFolderAndNamespace.CSharpMatchFolderAndNamespaceDiagnosticAnalyzer, Microsoft.CodeAnalysis.CSharp.CodeFixes.MatchFolderAndNamespace.CSharpChangeNamespaceToMatchFolderCodeFixProvider>; namespace Microsoft.CodeAnalysis.CSharp.Analyzers.UnitTests.MatchFolderAndNamespace { public class CSharpMatchFolderAndNamespaceTests { private static readonly string Directory = Path.Combine("Test", "Directory"); // DefaultNamespace gets exposed as RootNamespace in the build properties private const string DefaultNamespace = "Test.Root.Namespace"; private static readonly string EditorConfig = @$" is_global=true build_property.ProjectDir = {Directory} build_property.RootNamespace = {DefaultNamespace} "; private static string CreateFolderPath(params string[] folders) => Path.Combine(Directory, Path.Combine(folders)); private static Task RunTestAsync(string fileName, string fileContents, string? directory = null, string? editorConfig = null, string? fixedCode = null) { var filePath = Path.Combine(directory ?? Directory, fileName); fixedCode ??= fileContents; return RunTestAsync( new[] { (filePath, fileContents) }, new[] { (filePath, fixedCode) }, editorConfig); } private static Task RunTestAsync(IEnumerable<(string, string)> originalSources, IEnumerable<(string, string)>? fixedSources = null, string? editorconfig = null) { var testState = new VerifyCS.Test { EditorConfig = editorconfig ?? EditorConfig, CodeFixTestBehaviors = CodeAnalysis.Testing.CodeFixTestBehaviors.SkipFixAllInDocumentCheck, LanguageVersion = LanguageVersion.CSharp10, }; foreach (var (fileName, content) in originalSources) testState.TestState.Sources.Add((fileName, content)); fixedSources ??= Array.Empty<(string, string)>(); foreach (var (fileName, content) in fixedSources) testState.FixedState.Sources.Add((fileName, content)); return testState.RunAsync(); } [Fact] public Task InvalidFolderName1_NoDiagnostic() { // No change namespace action because the folder name is not valid identifier var folder = CreateFolderPath(new[] { "3B", "C" }); var code = @" namespace A.B { class Class1 { } }"; return RunTestAsync( "File1.cs", code, directory: folder); } [Fact] public Task InvalidFolderName1_NoDiagnostic_FileScopedNamespace() { // No change namespace action because the folder name is not valid identifier var folder = CreateFolderPath(new[] { "3B", "C" }); var code = @" namespace A.B; class Class1 { } "; return RunTestAsync( "File1.cs", code, directory: folder); } [Fact] public Task InvalidFolderName2_NoDiagnostic() { // No change namespace action because the folder name is not valid identifier var folder = CreateFolderPath(new[] { "B.3C", "D" }); var code = @" namespace A.B { class Class1 { } }"; return RunTestAsync( "File1.cs", code, directory: folder); } [Fact] public Task InvalidFolderName3_NoDiagnostic() { // No change namespace action because the folder name is not valid identifier var folder = CreateFolderPath(new[] { ".folder", "..subfolder", "name" }); var code = @" namespace A.B { class Class1 { } }"; return RunTestAsync( "File1.cs", code, directory: folder); } [Fact] public Task CaseInsensitiveMatch_NoDiagnostic() { var folder = CreateFolderPath(new[] { "A", "B" }); var code = @$" namespace {DefaultNamespace}.a.b {{ class Class1 {{ }} }}"; return RunTestAsync( "File1.cs", code, directory: folder); } [Fact] public async Task SingleDocumentNoReference() { var folder = CreateFolderPath("B", "C"); var code = @"namespace [|A.B|] { class Class1 { } }"; var fixedCode = @$"namespace {DefaultNamespace}.B.C {{ class Class1 {{ }} }}"; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder, fixedCode: fixedCode); } [Fact] public async Task SingleDocumentNoReference_FileScopedNamespace() { var folder = CreateFolderPath("B", "C"); var code = @"namespace [|A.B|]; class Class1 { } "; var fixedCode = @$"namespace {DefaultNamespace}.B.C; class Class1 {{ }} "; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder, fixedCode: fixedCode); } [Fact] public async Task SingleDocumentNoReference_NoDefaultNamespace() { var editorConfig = @$" is_global=true build_property.ProjectDir = {Directory} "; var folder = CreateFolderPath("B", "C"); var code = @"namespace [|A.B|] { class Class1 { } }"; var fixedCode = @$"namespace B.C {{ class Class1 {{ }} }}"; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder, fixedCode: fixedCode, editorConfig: editorConfig); } [Fact] public async Task SingleDocumentNoReference_NoDefaultNamespace_FileScopedNamespace() { var editorConfig = @$" is_global=true build_property.ProjectDir = {Directory} "; var folder = CreateFolderPath("B", "C"); var code = @"namespace [|A.B|]; class Class1 { } "; var fixedCode = @$"namespace B.C; class Class1 {{ }} "; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder, fixedCode: fixedCode, editorConfig: editorConfig); } [Fact] public async Task NamespaceWithSpaces_NoDiagnostic() { var folder = CreateFolderPath("A", "B"); var code = @$"namespace {DefaultNamespace}.A . B {{ class Class1 {{ }} }}"; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder); } [Fact] public async Task NestedNamespaces_NoDiagnostic() { // The code fix doesn't currently support nested namespaces for sync, so // diagnostic does not report. var folder = CreateFolderPath("B", "C"); var code = @"namespace A.B { namespace C.D { class CDClass { } } class ABClass { } }"; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder); } [Fact] public async Task PartialTypeWithMultipleDeclarations_NoDiagnostic() { // The code fix doesn't currently support nested namespaces for sync, so // diagnostic does not report. var folder = CreateFolderPath("B", "C"); var code1 = @"namespace A.B { partial class ABClass { void M1() {} } }"; var code2 = @"namespace A.B { partial class ABClass { void M2() {} } }"; var sources = new[] { (Path.Combine(folder, "ABClass1.cs"), code1), (Path.Combine(folder, "ABClass2.cs"), code2), }; await RunTestAsync(sources); } [Fact] public async Task FileNotInProjectFolder_NoDiagnostic() { // Default directory is Test\Directory for the project, // putting the file outside the directory should have no // diagnostic shown. var folder = Path.Combine("B", "C"); var code = $@"namespace A.B {{ class ABClass {{ }} }}"; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder); } [Fact] public async Task SingleDocumentLocalReference() { var @namespace = "Bar.Baz"; var folder = CreateFolderPath("A", "B", "C"); var code = $@" namespace [|{@namespace}|] {{ delegate void D1(); interface Class1 {{ void M1(); }} class Class2 : {@namespace}.Class1 {{ {@namespace}.D1 d; void {@namespace}.Class1.M1(){{}} }} }}"; var expected = @$"namespace {DefaultNamespace}.A.B.C {{ delegate void D1(); interface Class1 {{ void M1(); }} class Class2 : Class1 {{ D1 d; void Class1.M1() {{ }} }} }}"; await RunTestAsync( "Class1.cs", code, folder, fixedCode: expected); } [Fact] public async Task ChangeUsingsInMultipleContainers() { var declaredNamespace = "Bar.Baz"; var folder = CreateFolderPath("A", "B", "C"); var code1 = $@"namespace [|{declaredNamespace}|] {{ class Class1 {{ }} }}"; var code2 = $@"namespace NS1 {{ using {declaredNamespace}; class Class2 {{ Class1 c2; }} namespace NS2 {{ using {declaredNamespace}; class Class2 {{ Class1 c1; }} }} }}"; var fixed1 = @$"namespace {DefaultNamespace}.A.B.C {{ class Class1 {{ }} }}"; var fixed2 = @$"namespace NS1 {{ using {DefaultNamespace}.A.B.C; class Class2 {{ Class1 c2; }} namespace NS2 {{ class Class2 {{ Class1 c1; }} }} }}"; var originalSources = new[] { (Path.Combine(folder, "Class1.cs"), code1), ("Class2.cs", code2) }; var fixedSources = new[] { (Path.Combine(folder, "Class1.cs"), fixed1), ("Class2.cs", fixed2) }; await RunTestAsync(originalSources, fixedSources); } [Fact] public async Task ChangeNamespace_WithAliasReferencesInOtherDocument() { var declaredNamespace = $"Bar.Baz"; var folder = CreateFolderPath("A", "B", "C"); var code1 = $@"namespace [|{declaredNamespace}|] {{ class Class1 {{ }} }}"; var code2 = $@" using System; using {declaredNamespace}; using Class1Alias = {declaredNamespace}.Class1; namespace Foo {{ class RefClass {{ private Class1Alias c1; }} }}"; var fixed1 = @$"namespace {DefaultNamespace}.A.B.C {{ class Class1 {{ }} }}"; var fixed2 = @$" using System; using Class1Alias = {DefaultNamespace}.A.B.C.Class1; namespace Foo {{ class RefClass {{ private Class1Alias c1; }} }}"; var originalSources = new[] { (Path.Combine(folder, "Class1.cs"), code1), ("Class2.cs", code2) }; var fixedSources = new[] { (Path.Combine(folder, "Class1.cs"), fixed1), ("Class2.cs", fixed2) }; await RunTestAsync(originalSources, fixedSources); } [Fact] public async Task FixAll() { var declaredNamespace = "Bar.Baz"; var folder1 = CreateFolderPath("A", "B", "C"); var fixedNamespace1 = $"{DefaultNamespace}.A.B.C"; var folder2 = CreateFolderPath("Second", "Folder", "Path"); var fixedNamespace2 = $"{DefaultNamespace}.Second.Folder.Path"; var folder3 = CreateFolderPath("Third", "Folder", "Path"); var fixedNamespace3 = $"{DefaultNamespace}.Third.Folder.Path"; var code1 = $@"namespace [|{declaredNamespace}|] {{ class Class1 {{ Class2 C2 {{ get; }} Class3 C3 {{ get; }} }} }}"; var fixed1 = $@"using {fixedNamespace2}; using {fixedNamespace3}; namespace {fixedNamespace1} {{ class Class1 {{ Class2 C2 {{ get; }} Class3 C3 {{ get; }} }} }}"; var code2 = $@"namespace [|{declaredNamespace}|] {{ class Class2 {{ Class1 C1 {{ get; }} Class3 C3 {{ get; }} }} }}"; var fixed2 = $@"using {fixedNamespace1}; using {fixedNamespace3}; namespace {fixedNamespace2} {{ class Class2 {{ Class1 C1 {{ get; }} Class3 C3 {{ get; }} }} }}"; var code3 = $@"namespace [|{declaredNamespace}|] {{ class Class3 {{ Class1 C1 {{ get; }} Class2 C2 {{ get; }} }} }}"; var fixed3 = $@"using {fixedNamespace1}; using {fixedNamespace2}; namespace {fixedNamespace3} {{ class Class3 {{ Class1 C1 {{ get; }} Class2 C2 {{ get; }} }} }}"; var sources = new[] { (Path.Combine(folder1, "Class1.cs"), code1), (Path.Combine(folder2, "Class2.cs"), code2), (Path.Combine(folder3, "Class3.cs"), code3), }; var fixedSources = new[] { (Path.Combine(folder1, "Class1.cs"), fixed1), (Path.Combine(folder2, "Class2.cs"), fixed2), (Path.Combine(folder3, "Class3.cs"), fixed3), }; await RunTestAsync(sources, fixedSources); } } }
// Licensed to the .NET Foundation under one or more 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.Threading.Tasks; using Xunit; using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier< Microsoft.CodeAnalysis.CSharp.Analyzers.MatchFolderAndNamespace.CSharpMatchFolderAndNamespaceDiagnosticAnalyzer, Microsoft.CodeAnalysis.CSharp.CodeFixes.MatchFolderAndNamespace.CSharpChangeNamespaceToMatchFolderCodeFixProvider>; namespace Microsoft.CodeAnalysis.CSharp.Analyzers.UnitTests.MatchFolderAndNamespace { public class CSharpMatchFolderAndNamespaceTests { private static readonly string Directory = Path.Combine("Test", "Directory"); // DefaultNamespace gets exposed as RootNamespace in the build properties private const string DefaultNamespace = "Test.Root.Namespace"; private static readonly string EditorConfig = @$" is_global=true build_property.ProjectDir = {Directory} build_property.RootNamespace = {DefaultNamespace} "; private static string CreateFolderPath(params string[] folders) => Path.Combine(Directory, Path.Combine(folders)); private static Task RunTestAsync(string fileName, string fileContents, string? directory = null, string? editorConfig = null, string? fixedCode = null) { var filePath = Path.Combine(directory ?? Directory, fileName); fixedCode ??= fileContents; return RunTestAsync( new[] { (filePath, fileContents) }, new[] { (filePath, fixedCode) }, editorConfig); } private static Task RunTestAsync(IEnumerable<(string, string)> originalSources, IEnumerable<(string, string)>? fixedSources = null, string? editorconfig = null) { var testState = new VerifyCS.Test { EditorConfig = editorconfig ?? EditorConfig, CodeFixTestBehaviors = CodeAnalysis.Testing.CodeFixTestBehaviors.SkipFixAllInDocumentCheck, LanguageVersion = LanguageVersion.CSharp10, }; foreach (var (fileName, content) in originalSources) testState.TestState.Sources.Add((fileName, content)); fixedSources ??= Array.Empty<(string, string)>(); foreach (var (fileName, content) in fixedSources) testState.FixedState.Sources.Add((fileName, content)); return testState.RunAsync(); } [Fact] public Task InvalidFolderName1_NoDiagnostic() { // No change namespace action because the folder name is not valid identifier var folder = CreateFolderPath(new[] { "3B", "C" }); var code = @" namespace A.B { class Class1 { } }"; return RunTestAsync( "File1.cs", code, directory: folder); } [Fact] public Task InvalidFolderName1_NoDiagnostic_FileScopedNamespace() { // No change namespace action because the folder name is not valid identifier var folder = CreateFolderPath(new[] { "3B", "C" }); var code = @" namespace A.B; class Class1 { } "; return RunTestAsync( "File1.cs", code, directory: folder); } [Fact] public Task InvalidFolderName2_NoDiagnostic() { // No change namespace action because the folder name is not valid identifier var folder = CreateFolderPath(new[] { "B.3C", "D" }); var code = @" namespace A.B { class Class1 { } }"; return RunTestAsync( "File1.cs", code, directory: folder); } [Fact] public Task InvalidFolderName3_NoDiagnostic() { // No change namespace action because the folder name is not valid identifier var folder = CreateFolderPath(new[] { ".folder", "..subfolder", "name" }); var code = @" namespace A.B { class Class1 { } }"; return RunTestAsync( "File1.cs", code, directory: folder); } [Fact] public Task CaseInsensitiveMatch_NoDiagnostic() { var folder = CreateFolderPath(new[] { "A", "B" }); var code = @$" namespace {DefaultNamespace}.a.b {{ class Class1 {{ }} }}"; return RunTestAsync( "File1.cs", code, directory: folder); } [Fact] public async Task SingleDocumentNoReference() { var folder = CreateFolderPath("B", "C"); var code = @"namespace [|A.B|] { class Class1 { } }"; var fixedCode = @$"namespace {DefaultNamespace}.B.C {{ class Class1 {{ }} }}"; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder, fixedCode: fixedCode); } [Fact] public async Task SingleDocumentNoReference_FileScopedNamespace() { var folder = CreateFolderPath("B", "C"); var code = @"namespace [|A.B|]; class Class1 { } "; var fixedCode = @$"namespace {DefaultNamespace}.B.C; class Class1 {{ }} "; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder, fixedCode: fixedCode); } [Fact] public async Task SingleDocumentNoReference_NoDefaultNamespace() { var editorConfig = @$" is_global=true build_property.ProjectDir = {Directory} "; var folder = CreateFolderPath("B", "C"); var code = @"namespace [|A.B|] { class Class1 { } }"; var fixedCode = @$"namespace B.C {{ class Class1 {{ }} }}"; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder, fixedCode: fixedCode, editorConfig: editorConfig); } [Fact] public async Task SingleDocumentNoReference_NoDefaultNamespace_FileScopedNamespace() { var editorConfig = @$" is_global=true build_property.ProjectDir = {Directory} "; var folder = CreateFolderPath("B", "C"); var code = @"namespace [|A.B|]; class Class1 { } "; var fixedCode = @$"namespace B.C; class Class1 {{ }} "; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder, fixedCode: fixedCode, editorConfig: editorConfig); } [Fact] public async Task NamespaceWithSpaces_NoDiagnostic() { var folder = CreateFolderPath("A", "B"); var code = @$"namespace {DefaultNamespace}.A . B {{ class Class1 {{ }} }}"; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder); } [Fact] public async Task NestedNamespaces_NoDiagnostic() { // The code fix doesn't currently support nested namespaces for sync, so // diagnostic does not report. var folder = CreateFolderPath("B", "C"); var code = @"namespace A.B { namespace C.D { class CDClass { } } class ABClass { } }"; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder); } [Fact] public async Task PartialTypeWithMultipleDeclarations_NoDiagnostic() { // The code fix doesn't currently support nested namespaces for sync, so // diagnostic does not report. var folder = CreateFolderPath("B", "C"); var code1 = @"namespace A.B { partial class ABClass { void M1() {} } }"; var code2 = @"namespace A.B { partial class ABClass { void M2() {} } }"; var sources = new[] { (Path.Combine(folder, "ABClass1.cs"), code1), (Path.Combine(folder, "ABClass2.cs"), code2), }; await RunTestAsync(sources); } [Fact] public async Task FileNotInProjectFolder_NoDiagnostic() { // Default directory is Test\Directory for the project, // putting the file outside the directory should have no // diagnostic shown. var folder = Path.Combine("B", "C"); var code = $@"namespace A.B {{ class ABClass {{ }} }}"; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder); } [Fact] public async Task SingleDocumentLocalReference() { var @namespace = "Bar.Baz"; var folder = CreateFolderPath("A", "B", "C"); var code = $@" namespace [|{@namespace}|] {{ delegate void D1(); interface Class1 {{ void M1(); }} class Class2 : {@namespace}.Class1 {{ {@namespace}.D1 d; void {@namespace}.Class1.M1(){{}} }} }}"; var expected = @$"namespace {DefaultNamespace}.A.B.C {{ delegate void D1(); interface Class1 {{ void M1(); }} class Class2 : Class1 {{ D1 d; void Class1.M1() {{ }} }} }}"; await RunTestAsync( "Class1.cs", code, folder, fixedCode: expected); } [Fact] public async Task ChangeUsingsInMultipleContainers() { var declaredNamespace = "Bar.Baz"; var folder = CreateFolderPath("A", "B", "C"); var code1 = $@"namespace [|{declaredNamespace}|] {{ class Class1 {{ }} }}"; var code2 = $@"namespace NS1 {{ using {declaredNamespace}; class Class2 {{ Class1 c2; }} namespace NS2 {{ using {declaredNamespace}; class Class2 {{ Class1 c1; }} }} }}"; var fixed1 = @$"namespace {DefaultNamespace}.A.B.C {{ class Class1 {{ }} }}"; var fixed2 = @$"namespace NS1 {{ using {DefaultNamespace}.A.B.C; class Class2 {{ Class1 c2; }} namespace NS2 {{ class Class2 {{ Class1 c1; }} }} }}"; var originalSources = new[] { (Path.Combine(folder, "Class1.cs"), code1), ("Class2.cs", code2) }; var fixedSources = new[] { (Path.Combine(folder, "Class1.cs"), fixed1), ("Class2.cs", fixed2) }; await RunTestAsync(originalSources, fixedSources); } [Fact] public async Task ChangeNamespace_WithAliasReferencesInOtherDocument() { var declaredNamespace = $"Bar.Baz"; var folder = CreateFolderPath("A", "B", "C"); var code1 = $@"namespace [|{declaredNamespace}|] {{ class Class1 {{ }} }}"; var code2 = $@" using System; using {declaredNamespace}; using Class1Alias = {declaredNamespace}.Class1; namespace Foo {{ class RefClass {{ private Class1Alias c1; }} }}"; var fixed1 = @$"namespace {DefaultNamespace}.A.B.C {{ class Class1 {{ }} }}"; var fixed2 = @$" using System; using Class1Alias = {DefaultNamespace}.A.B.C.Class1; namespace Foo {{ class RefClass {{ private Class1Alias c1; }} }}"; var originalSources = new[] { (Path.Combine(folder, "Class1.cs"), code1), ("Class2.cs", code2) }; var fixedSources = new[] { (Path.Combine(folder, "Class1.cs"), fixed1), ("Class2.cs", fixed2) }; await RunTestAsync(originalSources, fixedSources); } [Fact] public async Task FixAll() { var declaredNamespace = "Bar.Baz"; var folder1 = CreateFolderPath("A", "B", "C"); var fixedNamespace1 = $"{DefaultNamespace}.A.B.C"; var folder2 = CreateFolderPath("Second", "Folder", "Path"); var fixedNamespace2 = $"{DefaultNamespace}.Second.Folder.Path"; var folder3 = CreateFolderPath("Third", "Folder", "Path"); var fixedNamespace3 = $"{DefaultNamespace}.Third.Folder.Path"; var code1 = $@"namespace [|{declaredNamespace}|] {{ class Class1 {{ Class2 C2 {{ get; }} Class3 C3 {{ get; }} }} }}"; var fixed1 = $@"using {fixedNamespace2}; using {fixedNamespace3}; namespace {fixedNamespace1} {{ class Class1 {{ Class2 C2 {{ get; }} Class3 C3 {{ get; }} }} }}"; var code2 = $@"namespace [|{declaredNamespace}|] {{ class Class2 {{ Class1 C1 {{ get; }} Class3 C3 {{ get; }} }} }}"; var fixed2 = $@"using {fixedNamespace1}; using {fixedNamespace3}; namespace {fixedNamespace2} {{ class Class2 {{ Class1 C1 {{ get; }} Class3 C3 {{ get; }} }} }}"; var code3 = $@"namespace [|{declaredNamespace}|] {{ class Class3 {{ Class1 C1 {{ get; }} Class2 C2 {{ get; }} }} }}"; var fixed3 = $@"using {fixedNamespace1}; using {fixedNamespace2}; namespace {fixedNamespace3} {{ class Class3 {{ Class1 C1 {{ get; }} Class2 C2 {{ get; }} }} }}"; var sources = new[] { (Path.Combine(folder1, "Class1.cs"), code1), (Path.Combine(folder2, "Class2.cs"), code2), (Path.Combine(folder3, "Class3.cs"), code3), }; var fixedSources = new[] { (Path.Combine(folder1, "Class1.cs"), fixed1), (Path.Combine(folder2, "Class2.cs"), fixed2), (Path.Combine(folder3, "Class3.cs"), fixed3), }; await RunTestAsync(sources, fixedSources); } } }
1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Analyzers/Core/Analyzers/MatchFolderAndNamespace/AbstractMatchFolderAndNamespaceDiagnosticAnalyzer.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.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Analyzers.MatchFolderAndNamespace { internal abstract class AbstractMatchFolderAndNamespaceDiagnosticAnalyzer<TSyntaxKind, TNamespaceSyntax> : AbstractBuiltInCodeStyleDiagnosticAnalyzer where TSyntaxKind : struct where TNamespaceSyntax : SyntaxNode { private static readonly LocalizableResourceString s_localizableTitle = new( nameof(AnalyzersResources.Namespace_does_not_match_folder_structure), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly LocalizableResourceString s_localizableInsideMessage = new( nameof(AnalyzersResources.Namespace_0_does_not_match_folder_structure_expected_1), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly SymbolDisplayFormat s_namespaceDisplayFormat = SymbolDisplayFormat .FullyQualifiedFormat .WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted); protected AbstractMatchFolderAndNamespaceDiagnosticAnalyzer() : base(IDEDiagnosticIds.MatchFolderAndNamespaceDiagnosticId, EnforceOnBuildValues.MatchFolderAndNamespace, CodeStyleOptions2.PreferNamespaceAndFolderMatchStructure, s_localizableTitle, s_localizableInsideMessage) { } protected abstract ISyntaxFacts GetSyntaxFacts(); protected abstract ImmutableArray<TSyntaxKind> GetSyntaxKindsToAnalyze(); protected sealed override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeNamespaceNode, GetSyntaxKindsToAnalyze()); public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; private void AnalyzeNamespaceNode(SyntaxNodeAnalysisContext context) { // It's ok to not have a rootnamespace property, but if it's there we want to use it correctly context.Options.AnalyzerConfigOptionsProvider.GlobalOptions.TryGetValue(MatchFolderAndNamespaceConstants.RootNamespaceOption, out var rootNamespace); // Project directory is a must to correctly get the relative path and construct a namespace if (!context.Options.AnalyzerConfigOptionsProvider.GlobalOptions.TryGetValue(MatchFolderAndNamespaceConstants.ProjectDirOption, out var projectDir) || string.IsNullOrEmpty(projectDir)) { return; } var namespaceDecl = (TNamespaceSyntax)context.Node; var symbol = context.SemanticModel.GetDeclaredSymbol(namespaceDecl); RoslynDebug.AssertNotNull(symbol); var currentNamespace = symbol.ToDisplayString(s_namespaceDisplayFormat); if (IsFileAndNamespaceMismatch(namespaceDecl, rootNamespace, projectDir, currentNamespace, out var targetNamespace) && IsFixSupported(context.SemanticModel, namespaceDecl, context.CancellationToken)) { var nameSyntax = GetSyntaxFacts().GetNameOfNamespaceDeclaration(namespaceDecl); RoslynDebug.AssertNotNull(nameSyntax); context.ReportDiagnostic(Diagnostic.Create( Descriptor, nameSyntax.GetLocation(), additionalLocations: null, properties: ImmutableDictionary<string, string?>.Empty.Add(MatchFolderAndNamespaceConstants.TargetNamespace, targetNamespace), messageArgs: new[] { currentNamespace, targetNamespace })); } } private bool IsFixSupported(SemanticModel semanticModel, TNamespaceSyntax namespaceDeclaration, CancellationToken cancellationToken) { var root = namespaceDeclaration.SyntaxTree.GetRoot(cancellationToken); // It should not be nested in other namespaces if (namespaceDeclaration.Ancestors().OfType<TNamespaceSyntax>().Any()) { return false; } // It should not contain a namespace var containsNamespace = namespaceDeclaration .DescendantNodes(n => n is TNamespaceSyntax) .OfType<TNamespaceSyntax>().Any(); if (containsNamespace) { return false; } // The current namespace should be valid var isCurrentNamespaceInvalid = GetSyntaxFacts() .GetNameOfNamespaceDeclaration(namespaceDeclaration) ?.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error) ?? false; if (isCurrentNamespaceInvalid) { return false; } // It should not contain partial classes with more than one instance in the semantic model. The // fixer does not support this scenario. var containsPartialType = ContainsPartialTypeWithMultipleDeclarations(namespaceDeclaration, semanticModel); if (containsPartialType) { return false; } return true; } private bool IsFileAndNamespaceMismatch( TNamespaceSyntax namespaceDeclaration, string? rootNamespace, string projectDir, string currentNamespace, [NotNullWhen(returnValue: true)] out string? targetNamespace) { if (!PathUtilities.IsChildPath(projectDir, namespaceDeclaration.SyntaxTree.FilePath)) { // The file does not exist within the project directory targetNamespace = null; return false; } var relativeDirectoryPath = PathUtilities.GetRelativePath( projectDir, PathUtilities.GetDirectoryName(namespaceDeclaration.SyntaxTree.FilePath)!); var folders = relativeDirectoryPath.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries); var expectedNamespace = PathMetadataUtilities.TryBuildNamespaceFromFolders(folders, GetSyntaxFacts(), rootNamespace); if (RoslynString.IsNullOrWhiteSpace(expectedNamespace) || expectedNamespace.Equals(currentNamespace, StringComparison.OrdinalIgnoreCase)) { // The namespace currently matches the folder structure or is invalid, in which case we don't want // to provide a diagnostic. targetNamespace = null; return false; } targetNamespace = expectedNamespace; return true; } /// <summary> /// Returns true if the namespace declaration contains one or more partial types with multiple declarations. /// </summary> protected bool ContainsPartialTypeWithMultipleDeclarations(TNamespaceSyntax namespaceDeclaration, SemanticModel semanticModel) { var syntaxFacts = GetSyntaxFacts(); var typeDeclarations = syntaxFacts.GetMembersOfNamespaceDeclaration(namespaceDeclaration) .Where(member => syntaxFacts.IsTypeDeclaration(member)); foreach (var typeDecl in typeDeclarations) { var symbol = semanticModel.GetDeclaredSymbol(typeDecl); // Simplify the check by assuming no multiple partial declarations in one document if (symbol is ITypeSymbol typeSymbol && typeSymbol.DeclaringSyntaxReferences.Length > 1) { return true; } } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Analyzers.MatchFolderAndNamespace { internal abstract class AbstractMatchFolderAndNamespaceDiagnosticAnalyzer<TSyntaxKind, TNamespaceSyntax> : AbstractBuiltInCodeStyleDiagnosticAnalyzer where TSyntaxKind : struct where TNamespaceSyntax : SyntaxNode { private static readonly LocalizableResourceString s_localizableTitle = new( nameof(AnalyzersResources.Namespace_does_not_match_folder_structure), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly LocalizableResourceString s_localizableInsideMessage = new( nameof(AnalyzersResources.Namespace_0_does_not_match_folder_structure_expected_1), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly SymbolDisplayFormat s_namespaceDisplayFormat = SymbolDisplayFormat .FullyQualifiedFormat .WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted); protected AbstractMatchFolderAndNamespaceDiagnosticAnalyzer() : base(IDEDiagnosticIds.MatchFolderAndNamespaceDiagnosticId, EnforceOnBuildValues.MatchFolderAndNamespace, CodeStyleOptions2.PreferNamespaceAndFolderMatchStructure, s_localizableTitle, s_localizableInsideMessage) { } protected abstract ISyntaxFacts GetSyntaxFacts(); protected abstract ImmutableArray<TSyntaxKind> GetSyntaxKindsToAnalyze(); protected sealed override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeNamespaceNode, GetSyntaxKindsToAnalyze()); public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; private void AnalyzeNamespaceNode(SyntaxNodeAnalysisContext context) { // It's ok to not have a rootnamespace property, but if it's there we want to use it correctly context.Options.AnalyzerConfigOptionsProvider.GlobalOptions.TryGetValue(MatchFolderAndNamespaceConstants.RootNamespaceOption, out var rootNamespace); // Project directory is a must to correctly get the relative path and construct a namespace if (!context.Options.AnalyzerConfigOptionsProvider.GlobalOptions.TryGetValue(MatchFolderAndNamespaceConstants.ProjectDirOption, out var projectDir) || string.IsNullOrEmpty(projectDir)) { return; } var namespaceDecl = (TNamespaceSyntax)context.Node; var symbol = context.SemanticModel.GetDeclaredSymbol(namespaceDecl); RoslynDebug.AssertNotNull(symbol); var currentNamespace = symbol.ToDisplayString(s_namespaceDisplayFormat); if (IsFileAndNamespaceMismatch(namespaceDecl, rootNamespace, projectDir, currentNamespace, out var targetNamespace) && IsFixSupported(context.SemanticModel, namespaceDecl, context.CancellationToken)) { var nameSyntax = GetSyntaxFacts().GetNameOfNamespaceDeclaration(namespaceDecl); RoslynDebug.AssertNotNull(nameSyntax); context.ReportDiagnostic(Diagnostic.Create( Descriptor, nameSyntax.GetLocation(), additionalLocations: null, properties: ImmutableDictionary<string, string?>.Empty.Add(MatchFolderAndNamespaceConstants.TargetNamespace, targetNamespace), messageArgs: new[] { currentNamespace, targetNamespace })); } } private bool IsFixSupported(SemanticModel semanticModel, TNamespaceSyntax namespaceDeclaration, CancellationToken cancellationToken) { var root = namespaceDeclaration.SyntaxTree.GetRoot(cancellationToken); // It should not be nested in other namespaces if (namespaceDeclaration.Ancestors().OfType<TNamespaceSyntax>().Any()) { return false; } // It should not contain a namespace var containsNamespace = namespaceDeclaration .DescendantNodes(n => n is TNamespaceSyntax) .OfType<TNamespaceSyntax>().Any(); if (containsNamespace) { return false; } // The current namespace should be valid var isCurrentNamespaceInvalid = GetSyntaxFacts() .GetNameOfNamespaceDeclaration(namespaceDeclaration) ?.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error) ?? false; if (isCurrentNamespaceInvalid) { return false; } // It should not contain partial classes with more than one instance in the semantic model. The // fixer does not support this scenario. var containsPartialType = ContainsPartialTypeWithMultipleDeclarations(namespaceDeclaration, semanticModel); if (containsPartialType) { return false; } return true; } private bool IsFileAndNamespaceMismatch( TNamespaceSyntax namespaceDeclaration, string? rootNamespace, string projectDir, string currentNamespace, [NotNullWhen(returnValue: true)] out string? targetNamespace) { if (!PathUtilities.IsChildPath(projectDir, namespaceDeclaration.SyntaxTree.FilePath)) { // The file does not exist within the project directory targetNamespace = null; return false; } var relativeDirectoryPath = PathUtilities.GetRelativePath( projectDir, PathUtilities.GetDirectoryName(namespaceDeclaration.SyntaxTree.FilePath)!); var folders = relativeDirectoryPath.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries); var expectedNamespace = PathMetadataUtilities.TryBuildNamespaceFromFolders(folders, GetSyntaxFacts(), rootNamespace); if (RoslynString.IsNullOrWhiteSpace(expectedNamespace) || expectedNamespace.Equals(currentNamespace, StringComparison.OrdinalIgnoreCase)) { // The namespace currently matches the folder structure or is invalid, in which case we don't want // to provide a diagnostic. targetNamespace = null; return false; } targetNamespace = expectedNamespace; return true; } /// <summary> /// Returns true if the namespace declaration contains one or more partial types with multiple declarations. /// </summary> protected bool ContainsPartialTypeWithMultipleDeclarations(TNamespaceSyntax namespaceDeclaration, SemanticModel semanticModel) { var syntaxFacts = GetSyntaxFacts(); var typeDeclarations = syntaxFacts.GetMembersOfNamespaceDeclaration(namespaceDeclaration) .Where(member => syntaxFacts.IsTypeDeclaration(member)); foreach (var typeDecl in typeDeclarations) { var symbol = semanticModel.GetDeclaredSymbol(typeDecl); // Simplify the check by assuming no multiple partial declarations in one document if (symbol is ITypeSymbol typeSymbol && typeSymbol.DeclaringSyntaxReferences.Length > 1) { return true; } } return false; } } }
1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/CodeActions/MoveType/MoveTypeTests.MoveToNewFile.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.MoveType { public partial class MoveTypeTests : CSharpMoveTypeTestsBase { [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestMissing_OnMatchingFileName() { var code = @"[||]class test1 { }"; await TestMissingInRegularAndScriptAsync(code); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestMissing_Nested_OnMatchingFileName_Simple() { var code = @"class outer { [||]class test1 { } }"; await TestMissingInRegularAndScriptAsync(code); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestMatchingFileName_CaseSensitive() { var code = @"[||]class Test1 { }"; await TestActionCountAsync(code, count: 2); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestForSpans1() { var code = @"[|clas|]s Class1 { } class Class2 { }"; await TestActionCountAsync(code, count: 3); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestForSpans2() { var code = @"[||]class Class1 { } class Class2 { }"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"class Class1 { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] [WorkItem(14008, "https://github.com/dotnet/roslyn/issues/14008")] public async Task TestMoveToNewFileWithFolders() { var code = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document Folders=""A\B""> [||]class Class1 { } class Class2 { } </Document> </Project> </Workspace>"; var codeAfterMove = @"class Class2 { } "; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"class Class1 { } "; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText, destinationDocumentContainers: ImmutableArray.Create("A", "B")); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestForSpans3() { var code = @"[|class Class1|] { } class Class2 { }"; await TestActionCountAsync(code, count: 3); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestForSpans4() { var code = @"class Class1[||] { } class Class2 { }"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"class Class1 { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithNoContainerNamespace() { var code = @"[||]class Class1 { } class Class2 { }"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"class Class1 { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithWithUsingsAndNoContainerNamespace() { var code = @"// Banner Text using System; [||]class Class1 { } class Class2 { }"; var codeAfterMove = @"// Banner Text using System; class Class2 { }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"// Banner Text class Class1 { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithWithMembers() { var code = @"// Banner Text using System; [||]class Class1 { void Print(int x) { Console.WriteLine(x); } } class Class2 { }"; var codeAfterMove = @"// Banner Text class Class2 { }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"// Banner Text using System; class Class1 { void Print(int x) { Console.WriteLine(x); } } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithWithMembers2() { var code = @"// Banner Text using System; [||]class Class1 { void Print(int x) { Console.WriteLine(x); } } class Class2 { void Print(int x) { Console.WriteLine(x); } }"; var codeAfterMove = @"// Banner Text using System; class Class2 { void Print(int x) { Console.WriteLine(x); } }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"// Banner Text using System; class Class1 { void Print(int x) { Console.WriteLine(x); } } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveAnInterface() { var code = @"[||]interface IMoveType { } class Class2 { }"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "IMoveType.cs"; var destinationDocumentText = @"interface IMoveType { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveAStruct() { var code = @"[||]struct MyStruct { } class Class2 { }"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "MyStruct.cs"; var destinationDocumentText = @"struct MyStruct { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveAnEnum() { var code = @"[||]enum MyEnum { } class Class2 { }"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "MyEnum.cs"; var destinationDocumentText = @"enum MyEnum { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithWithContainerNamespace() { var code = @"namespace N1 { [||]class Class1 { } class Class2 { } }"; var codeAfterMove = @"namespace N1 { class Class2 { } }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"namespace N1 { class Class1 { } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveNestedTypeToNewFile_Simple() { var code = @"namespace N1 { class Class1 { [||]class Class2 { } } }"; var codeAfterMove = @"namespace N1 { partial class Class1 { } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { class Class2 { } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveNestedTypePreserveModifiers() { var code = @"namespace N1 { abstract class Class1 { [||]class Class2 { } } }"; var codeAfterMove = @"namespace N1 { abstract partial class Class1 { } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { abstract partial class Class1 { class Class2 { } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] [WorkItem(14004, "https://github.com/dotnet/roslyn/issues/14004")] public async Task MoveNestedTypeToNewFile_Attributes1() { var code = @"namespace N1 { [Outer] class Class1 { [Inner] [||]class Class2 { } } }"; var codeAfterMove = @"namespace N1 { [Outer] partial class Class1 { } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { [Inner] class Class2 { } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] [WorkItem(14484, "https://github.com/dotnet/roslyn/issues/14484")] public async Task MoveNestedTypeToNewFile_Comments1() { var code = @"namespace N1 { /// Outer doc comment. class Class1 { /// Inner doc comment [||]class Class2 { } } }"; var codeAfterMove = @"namespace N1 { /// Outer doc comment. partial class Class1 { } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { /// Inner doc comment class Class2 { } } }"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveNestedTypeToNewFile_Simple_DottedName() { var code = @"namespace N1 { class Class1 { [||]class Class2 { } } }"; var codeAfterMove = @"namespace N1 { partial class Class1 { } }"; var expectedDocumentName = "Class1.Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { class Class2 { } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText, index: 1); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveNestedTypeToNewFile_ParentHasOtherMembers() { var code = @"namespace N1 { class Class1 { private int _field1; [||]class Class2 { } public void Method1() { } } }"; var codeAfterMove = @"namespace N1 { partial class Class1 { private int _field1; public void Method1() { } } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { class Class2 { } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveNestedTypeToNewFile_HasOtherTopLevelMembers() { var code = @"namespace N1 { class Class1 { private int _field1; [||]class Class2 { } public void Method1() { } } internal class Class3 { private void Method1() { } } }"; var codeAfterMove = @"namespace N1 { partial class Class1 { private int _field1; public void Method1() { } } internal class Class3 { private void Method1() { } } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { class Class2 { } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveNestedTypeToNewFile_HasMembers() { var code = @"namespace N1 { class Class1 { private int _field1; [||]class Class2 { private string _field1; public void InnerMethod() { } } public void Method1() { } } }"; var codeAfterMove = @"namespace N1 { partial class Class1 { private int _field1; public void Method1() { } } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { class Class2 { private string _field1; public void InnerMethod() { } } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] [WorkItem(13969, "https://github.com/dotnet/roslyn/issues/13969")] public async Task MoveTypeInFileWithComplexHierarchy() { var code = @"namespace OuterN1.N1 { namespace InnerN2.N2 { class OuterClass1 { class InnerClass2 { } } } namespace InnerN3.N3 { class OuterClass2 { [||]class InnerClass2 { class InnerClass3 { } } class InnerClass4 { } } class OuterClass3 { } } } namespace OuterN2.N2 { namespace InnerN3.N3 { class OuterClass5 { class InnerClass6 { } } } } "; var codeAfterMove = @"namespace OuterN1.N1 { namespace InnerN2.N2 { class OuterClass1 { class InnerClass2 { } } } namespace InnerN3.N3 { partial class OuterClass2 { class InnerClass4 { } } class OuterClass3 { } } } namespace OuterN2.N2 { namespace InnerN3.N3 { class OuterClass5 { class InnerClass6 { } } } } "; var expectedDocumentName = "InnerClass2.cs"; var destinationDocumentText = @"namespace OuterN1.N1 { namespace InnerN3.N3 { partial class OuterClass2 { class InnerClass2 { class InnerClass3 { } } } } } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeUsings1() { var code = @" // Only used by inner type. using System; // Unused by both types. using System.Collections; class Outer { [||]class Inner { DateTime d; } }"; var codeAfterMove = @" // Only used by inner type. // Unused by both types. using System.Collections; partial class Outer { }"; var expectedDocumentName = "Inner.cs"; var destinationDocumentText = @" // Only used by inner type. using System; // Unused by both types. partial class Outer { class Inner { DateTime d; } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(16283, "https://github.com/dotnet/roslyn/issues/16283")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestLeadingTrivia1() { var code = @" class Outer { class Inner1 { } [||]class Inner2 { } }"; var codeAfterMove = @" partial class Outer { class Inner1 { } }"; var expectedDocumentName = "Inner2.cs"; var destinationDocumentText = @" partial class Outer { class Inner2 { } }"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(17171, "https://github.com/dotnet/roslyn/issues/17171")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestInsertFinalNewLine() { var code = @" class Outer { class Inner1 { } [||]class Inner2 { } }"; var codeAfterMove = @" partial class Outer { class Inner1 { } }"; var expectedDocumentName = "Inner2.cs"; var destinationDocumentText = @" partial class Outer { class Inner2 { } } "; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText, onAfterWorkspaceCreated: w => { w.TryApplyChanges(w.CurrentSolution.WithOptions(w.CurrentSolution.Options.WithChangedOption(FormattingOptions2.InsertFinalNewLine, true))); }); } [WorkItem(17171, "https://github.com/dotnet/roslyn/issues/17171")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestInsertFinalNewLine2() { var code = @" class Outer { class Inner1 { } [||]class Inner2 { } }"; var codeAfterMove = @" partial class Outer { class Inner1 { } }"; var expectedDocumentName = "Inner2.cs"; var destinationDocumentText = @" partial class Outer { class Inner2 { } }"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText, onAfterWorkspaceCreated: w => { w.TryApplyChanges(w.CurrentSolution.WithOptions(w.CurrentSolution.Options.WithChangedOption(FormattingOptions2.InsertFinalNewLine, false))); }); } [WorkItem(16282, "https://github.com/dotnet/roslyn/issues/16282")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeRemoveOuterInheritanceTypes() { var code = @" class Outer : IComparable { [||]class Inner : IWhatever { DateTime d; } }"; var codeAfterMove = @" partial class Outer : IComparable { }"; var expectedDocumentName = "Inner.cs"; var destinationDocumentText = @" partial class Outer { class Inner : IWhatever { DateTime d; } }"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(17930, "https://github.com/dotnet/roslyn/issues/17930")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithDirectives1() { var code = @"using System; namespace N { class Program { static void Main() { } } } #if true public class [||]Inner { } #endif"; var codeAfterMove = @"using System; namespace N { class Program { static void Main() { } } } #if true #endif"; var expectedDocumentName = "Inner.cs"; var destinationDocumentText = @" #if true public class Inner { } #endif"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(17930, "https://github.com/dotnet/roslyn/issues/17930")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithDirectives2() { var code = @"using System; namespace N { class Program { static void Main() { } #if true public class [||]Inner { } #endif } }"; var codeAfterMove = @"using System; namespace N { partial class Program { static void Main() { } #if true #endif } }"; var expectedDocumentName = "Inner.cs"; var destinationDocumentText = @"namespace N { partial class Program { #if true public class Inner { } #endif } }"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(21456, "https://github.com/dotnet/roslyn/issues/21456")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestLeadingBlankLines1() { var code = @"// Banner Text using System; [||]class Class1 { void Foo() { Console.WriteLine(); } } class Class2 { void Foo() { Console.WriteLine(); } } "; var codeAfterMove = @"// Banner Text using System; class Class2 { void Foo() { Console.WriteLine(); } } "; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"// Banner Text using System; class Class1 { void Foo() { Console.WriteLine(); } } "; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(21456, "https://github.com/dotnet/roslyn/issues/21456")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestLeadingBlankLines2() { var code = @"// Banner Text using System; class Class1 { void Foo() { Console.WriteLine(); } } [||]class Class2 { void Foo() { Console.WriteLine(); } } "; var codeAfterMove = @"// Banner Text using System; class Class1 { void Foo() { Console.WriteLine(); } } "; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"// Banner Text using System; class Class2 { void Foo() { Console.WriteLine(); } } "; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(31377, "https://github.com/dotnet/roslyn/issues/31377")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestLeadingCommentInContainer() { var code = @"// Banner Text using System; class Class1 // Leading comment { class [||]Class2 { } void Foo() { Console.WriteLine(); } public int I() => 5; } "; var codeAfterMove = @"// Banner Text using System; partial class Class1 // Leading comment { void Foo() { Console.WriteLine(); } public int I() => 5; } "; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"// Banner Text partial class Class1 { class Class2 { } } "; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(31377, "https://github.com/dotnet/roslyn/issues/31377")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestLeadingCommentInContainer2() { var code = @"// Banner Text using System; class Class1 { // Leading comment class [||]Class2 { } void Foo() { Console.WriteLine(); } public int I() => 5; } "; var codeAfterMove = @"// Banner Text using System; partial class Class1 { // Leading comment void Foo() { Console.WriteLine(); } public int I() => 5; } "; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"// Banner Text partial class Class1 { class Class2 { } } "; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(31377, "https://github.com/dotnet/roslyn/issues/31377")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestTrailingCommentInContainer() { var code = @"// Banner Text using System; class Class1 { class [||]Class2 { } void Foo() { Console.WriteLine(); } public int I() => 5; // End of class document } "; var codeAfterMove = @"// Banner Text using System; partial class Class1 { void Foo() { Console.WriteLine(); } public int I() => 5; // End of class document } "; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"// Banner Text partial class Class1 { class Class2 { } } "; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(31377, "https://github.com/dotnet/roslyn/issues/31377")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestTrailingCommentInContainer2() { var code = @"// Banner Text using System; class Class1 { class [||]Class2 { } void Foo() { Console.WriteLine(); } public int I() => 5; } // End of class document "; var codeAfterMove = @"// Banner Text using System; partial class Class1 { void Foo() { Console.WriteLine(); } public int I() => 5; } // End of class document "; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"// Banner Text partial class Class1 { class Class2 { } }"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(50329, "https://github.com/dotnet/roslyn/issues/50329")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveRecordToNewFilePreserveUsings() { var code = @"using System; [||]record CacheContext(String Message); class Program { }"; var codeAfterMove = @"class Program { }"; var expectedDocumentName = "CacheContext.cs"; var destinationDocumentText = @"using System; record CacheContext(String Message); "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveClassInTopLevelStatements() { var code = @" using ConsoleApp1; using System; var c = new C(); Console.WriteLine(c.Hello); class [||]C { public string Hello => ""Hello""; }"; var codeAfterMove = @" using ConsoleApp1; using System; var c = new C(); Console.WriteLine(c.Hello); "; var expectedDocumentName = "C.cs"; var destinationDocumentText = @"class C { public string Hello => ""Hello""; }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MissingInTopLevelStatementsOnly() { var code = @" using ConsoleApp1; using System; var c = new object(); [||]Console.WriteLine(c.ToString()); "; await TestMissingAsync(code); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.MoveType { public partial class MoveTypeTests : CSharpMoveTypeTestsBase { [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestMissing_OnMatchingFileName() { var code = @"[||]class test1 { }"; await TestMissingInRegularAndScriptAsync(code); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestMissing_Nested_OnMatchingFileName_Simple() { var code = @"class outer { [||]class test1 { } }"; await TestMissingInRegularAndScriptAsync(code); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestMatchingFileName_CaseSensitive() { var code = @"[||]class Test1 { }"; await TestActionCountAsync(code, count: 2); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestForSpans1() { var code = @"[|clas|]s Class1 { } class Class2 { }"; await TestActionCountAsync(code, count: 3); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestForSpans2() { var code = @"[||]class Class1 { } class Class2 { }"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"class Class1 { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] [WorkItem(14008, "https://github.com/dotnet/roslyn/issues/14008")] public async Task TestMoveToNewFileWithFolders() { var code = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document Folders=""A\B""> [||]class Class1 { } class Class2 { } </Document> </Project> </Workspace>"; var codeAfterMove = @"class Class2 { } "; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"class Class1 { } "; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText, destinationDocumentContainers: ImmutableArray.Create("A", "B")); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestForSpans3() { var code = @"[|class Class1|] { } class Class2 { }"; await TestActionCountAsync(code, count: 3); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestForSpans4() { var code = @"class Class1[||] { } class Class2 { }"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"class Class1 { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithNoContainerNamespace() { var code = @"[||]class Class1 { } class Class2 { }"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"class Class1 { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithWithUsingsAndNoContainerNamespace() { var code = @"// Banner Text using System; [||]class Class1 { } class Class2 { }"; var codeAfterMove = @"// Banner Text using System; class Class2 { }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"// Banner Text class Class1 { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithWithMembers() { var code = @"// Banner Text using System; [||]class Class1 { void Print(int x) { Console.WriteLine(x); } } class Class2 { }"; var codeAfterMove = @"// Banner Text class Class2 { }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"// Banner Text using System; class Class1 { void Print(int x) { Console.WriteLine(x); } } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithWithMembers2() { var code = @"// Banner Text using System; [||]class Class1 { void Print(int x) { Console.WriteLine(x); } } class Class2 { void Print(int x) { Console.WriteLine(x); } }"; var codeAfterMove = @"// Banner Text using System; class Class2 { void Print(int x) { Console.WriteLine(x); } }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"// Banner Text using System; class Class1 { void Print(int x) { Console.WriteLine(x); } } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveAnInterface() { var code = @"[||]interface IMoveType { } class Class2 { }"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "IMoveType.cs"; var destinationDocumentText = @"interface IMoveType { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveAStruct() { var code = @"[||]struct MyStruct { } class Class2 { }"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "MyStruct.cs"; var destinationDocumentText = @"struct MyStruct { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveAnEnum() { var code = @"[||]enum MyEnum { } class Class2 { }"; var codeAfterMove = @"class Class2 { }"; var expectedDocumentName = "MyEnum.cs"; var destinationDocumentText = @"enum MyEnum { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithWithContainerNamespace() { var code = @"namespace N1 { [||]class Class1 { } class Class2 { } }"; var codeAfterMove = @"namespace N1 { class Class2 { } }"; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"namespace N1 { class Class1 { } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithWithFileScopedNamespace() { var code = @"namespace N1; [||]class Class1 { } class Class2 { } "; var codeAfterMove = @"namespace N1; class Class2 { } "; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"namespace N1; class Class1 { } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveNestedTypeToNewFile_Simple() { var code = @"namespace N1 { class Class1 { [||]class Class2 { } } }"; var codeAfterMove = @"namespace N1 { partial class Class1 { } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { class Class2 { } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveNestedTypePreserveModifiers() { var code = @"namespace N1 { abstract class Class1 { [||]class Class2 { } } }"; var codeAfterMove = @"namespace N1 { abstract partial class Class1 { } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { abstract partial class Class1 { class Class2 { } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] [WorkItem(14004, "https://github.com/dotnet/roslyn/issues/14004")] public async Task MoveNestedTypeToNewFile_Attributes1() { var code = @"namespace N1 { [Outer] class Class1 { [Inner] [||]class Class2 { } } }"; var codeAfterMove = @"namespace N1 { [Outer] partial class Class1 { } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { [Inner] class Class2 { } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] [WorkItem(14484, "https://github.com/dotnet/roslyn/issues/14484")] public async Task MoveNestedTypeToNewFile_Comments1() { var code = @"namespace N1 { /// Outer doc comment. class Class1 { /// Inner doc comment [||]class Class2 { } } }"; var codeAfterMove = @"namespace N1 { /// Outer doc comment. partial class Class1 { } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { /// Inner doc comment class Class2 { } } }"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveNestedTypeToNewFile_Simple_DottedName() { var code = @"namespace N1 { class Class1 { [||]class Class2 { } } }"; var codeAfterMove = @"namespace N1 { partial class Class1 { } }"; var expectedDocumentName = "Class1.Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { class Class2 { } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText, index: 1); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveNestedTypeToNewFile_ParentHasOtherMembers() { var code = @"namespace N1 { class Class1 { private int _field1; [||]class Class2 { } public void Method1() { } } }"; var codeAfterMove = @"namespace N1 { partial class Class1 { private int _field1; public void Method1() { } } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { class Class2 { } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveNestedTypeToNewFile_HasOtherTopLevelMembers() { var code = @"namespace N1 { class Class1 { private int _field1; [||]class Class2 { } public void Method1() { } } internal class Class3 { private void Method1() { } } }"; var codeAfterMove = @"namespace N1 { partial class Class1 { private int _field1; public void Method1() { } } internal class Class3 { private void Method1() { } } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { class Class2 { } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveNestedTypeToNewFile_HasMembers() { var code = @"namespace N1 { class Class1 { private int _field1; [||]class Class2 { private string _field1; public void InnerMethod() { } } public void Method1() { } } }"; var codeAfterMove = @"namespace N1 { partial class Class1 { private int _field1; public void Method1() { } } }"; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"namespace N1 { partial class Class1 { class Class2 { private string _field1; public void InnerMethod() { } } } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] [WorkItem(13969, "https://github.com/dotnet/roslyn/issues/13969")] public async Task MoveTypeInFileWithComplexHierarchy() { var code = @"namespace OuterN1.N1 { namespace InnerN2.N2 { class OuterClass1 { class InnerClass2 { } } } namespace InnerN3.N3 { class OuterClass2 { [||]class InnerClass2 { class InnerClass3 { } } class InnerClass4 { } } class OuterClass3 { } } } namespace OuterN2.N2 { namespace InnerN3.N3 { class OuterClass5 { class InnerClass6 { } } } } "; var codeAfterMove = @"namespace OuterN1.N1 { namespace InnerN2.N2 { class OuterClass1 { class InnerClass2 { } } } namespace InnerN3.N3 { partial class OuterClass2 { class InnerClass4 { } } class OuterClass3 { } } } namespace OuterN2.N2 { namespace InnerN3.N3 { class OuterClass5 { class InnerClass6 { } } } } "; var expectedDocumentName = "InnerClass2.cs"; var destinationDocumentText = @"namespace OuterN1.N1 { namespace InnerN3.N3 { partial class OuterClass2 { class InnerClass2 { class InnerClass3 { } } } } } "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeUsings1() { var code = @" // Only used by inner type. using System; // Unused by both types. using System.Collections; class Outer { [||]class Inner { DateTime d; } }"; var codeAfterMove = @" // Only used by inner type. // Unused by both types. using System.Collections; partial class Outer { }"; var expectedDocumentName = "Inner.cs"; var destinationDocumentText = @" // Only used by inner type. using System; // Unused by both types. partial class Outer { class Inner { DateTime d; } }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(16283, "https://github.com/dotnet/roslyn/issues/16283")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestLeadingTrivia1() { var code = @" class Outer { class Inner1 { } [||]class Inner2 { } }"; var codeAfterMove = @" partial class Outer { class Inner1 { } }"; var expectedDocumentName = "Inner2.cs"; var destinationDocumentText = @" partial class Outer { class Inner2 { } }"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(17171, "https://github.com/dotnet/roslyn/issues/17171")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestInsertFinalNewLine() { var code = @" class Outer { class Inner1 { } [||]class Inner2 { } }"; var codeAfterMove = @" partial class Outer { class Inner1 { } }"; var expectedDocumentName = "Inner2.cs"; var destinationDocumentText = @" partial class Outer { class Inner2 { } } "; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText, onAfterWorkspaceCreated: w => { w.TryApplyChanges(w.CurrentSolution.WithOptions(w.CurrentSolution.Options.WithChangedOption(FormattingOptions2.InsertFinalNewLine, true))); }); } [WorkItem(17171, "https://github.com/dotnet/roslyn/issues/17171")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestInsertFinalNewLine2() { var code = @" class Outer { class Inner1 { } [||]class Inner2 { } }"; var codeAfterMove = @" partial class Outer { class Inner1 { } }"; var expectedDocumentName = "Inner2.cs"; var destinationDocumentText = @" partial class Outer { class Inner2 { } }"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText, onAfterWorkspaceCreated: w => { w.TryApplyChanges(w.CurrentSolution.WithOptions(w.CurrentSolution.Options.WithChangedOption(FormattingOptions2.InsertFinalNewLine, false))); }); } [WorkItem(16282, "https://github.com/dotnet/roslyn/issues/16282")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeRemoveOuterInheritanceTypes() { var code = @" class Outer : IComparable { [||]class Inner : IWhatever { DateTime d; } }"; var codeAfterMove = @" partial class Outer : IComparable { }"; var expectedDocumentName = "Inner.cs"; var destinationDocumentText = @" partial class Outer { class Inner : IWhatever { DateTime d; } }"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(17930, "https://github.com/dotnet/roslyn/issues/17930")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithDirectives1() { var code = @"using System; namespace N { class Program { static void Main() { } } } #if true public class [||]Inner { } #endif"; var codeAfterMove = @"using System; namespace N { class Program { static void Main() { } } } #if true #endif"; var expectedDocumentName = "Inner.cs"; var destinationDocumentText = @" #if true public class Inner { } #endif"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(17930, "https://github.com/dotnet/roslyn/issues/17930")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveTypeWithDirectives2() { var code = @"using System; namespace N { class Program { static void Main() { } #if true public class [||]Inner { } #endif } }"; var codeAfterMove = @"using System; namespace N { partial class Program { static void Main() { } #if true #endif } }"; var expectedDocumentName = "Inner.cs"; var destinationDocumentText = @"namespace N { partial class Program { #if true public class Inner { } #endif } }"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(21456, "https://github.com/dotnet/roslyn/issues/21456")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestLeadingBlankLines1() { var code = @"// Banner Text using System; [||]class Class1 { void Foo() { Console.WriteLine(); } } class Class2 { void Foo() { Console.WriteLine(); } } "; var codeAfterMove = @"// Banner Text using System; class Class2 { void Foo() { Console.WriteLine(); } } "; var expectedDocumentName = "Class1.cs"; var destinationDocumentText = @"// Banner Text using System; class Class1 { void Foo() { Console.WriteLine(); } } "; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(21456, "https://github.com/dotnet/roslyn/issues/21456")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestLeadingBlankLines2() { var code = @"// Banner Text using System; class Class1 { void Foo() { Console.WriteLine(); } } [||]class Class2 { void Foo() { Console.WriteLine(); } } "; var codeAfterMove = @"// Banner Text using System; class Class1 { void Foo() { Console.WriteLine(); } } "; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"// Banner Text using System; class Class2 { void Foo() { Console.WriteLine(); } } "; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(31377, "https://github.com/dotnet/roslyn/issues/31377")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestLeadingCommentInContainer() { var code = @"// Banner Text using System; class Class1 // Leading comment { class [||]Class2 { } void Foo() { Console.WriteLine(); } public int I() => 5; } "; var codeAfterMove = @"// Banner Text using System; partial class Class1 // Leading comment { void Foo() { Console.WriteLine(); } public int I() => 5; } "; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"// Banner Text partial class Class1 { class Class2 { } } "; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(31377, "https://github.com/dotnet/roslyn/issues/31377")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestLeadingCommentInContainer2() { var code = @"// Banner Text using System; class Class1 { // Leading comment class [||]Class2 { } void Foo() { Console.WriteLine(); } public int I() => 5; } "; var codeAfterMove = @"// Banner Text using System; partial class Class1 { // Leading comment void Foo() { Console.WriteLine(); } public int I() => 5; } "; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"// Banner Text partial class Class1 { class Class2 { } } "; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(31377, "https://github.com/dotnet/roslyn/issues/31377")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestTrailingCommentInContainer() { var code = @"// Banner Text using System; class Class1 { class [||]Class2 { } void Foo() { Console.WriteLine(); } public int I() => 5; // End of class document } "; var codeAfterMove = @"// Banner Text using System; partial class Class1 { void Foo() { Console.WriteLine(); } public int I() => 5; // End of class document } "; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"// Banner Text partial class Class1 { class Class2 { } } "; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(31377, "https://github.com/dotnet/roslyn/issues/31377")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task TestTrailingCommentInContainer2() { var code = @"// Banner Text using System; class Class1 { class [||]Class2 { } void Foo() { Console.WriteLine(); } public int I() => 5; } // End of class document "; var codeAfterMove = @"// Banner Text using System; partial class Class1 { void Foo() { Console.WriteLine(); } public int I() => 5; } // End of class document "; var expectedDocumentName = "Class2.cs"; var destinationDocumentText = @"// Banner Text partial class Class1 { class Class2 { } }"; await TestMoveTypeToNewFileAsync( code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WorkItem(50329, "https://github.com/dotnet/roslyn/issues/50329")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveRecordToNewFilePreserveUsings() { var code = @"using System; [||]record CacheContext(String Message); class Program { }"; var codeAfterMove = @"class Program { }"; var expectedDocumentName = "CacheContext.cs"; var destinationDocumentText = @"using System; record CacheContext(String Message); "; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MoveClassInTopLevelStatements() { var code = @" using ConsoleApp1; using System; var c = new C(); Console.WriteLine(c.Hello); class [||]C { public string Hello => ""Hello""; }"; var codeAfterMove = @" using ConsoleApp1; using System; var c = new C(); Console.WriteLine(c.Hello); "; var expectedDocumentName = "C.cs"; var destinationDocumentText = @"class C { public string Hello => ""Hello""; }"; await TestMoveTypeToNewFileAsync(code, codeAfterMove, expectedDocumentName, destinationDocumentText); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)] public async Task MissingInTopLevelStatementsOnly() { var code = @" using ConsoleApp1; using System; var c = new object(); [||]Console.WriteLine(c.ToString()); "; await TestMissingAsync(code); } } }
1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/Debugging/LocationInfoGetterTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Debugging; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Debugging { [UseExportProvider] public class LocationInfoGetterTests { private static async Task TestAsync(string markup, string expectedName, int expectedLineOffset, CSharpParseOptions parseOptions = null) { using var workspace = TestWorkspace.CreateCSharp(markup, parseOptions); var testDocument = workspace.Documents.Single(); var position = testDocument.CursorPosition.Value; var locationInfo = await LocationInfoGetter.GetInfoAsync( workspace.CurrentSolution.Projects.Single().Documents.Single(), position, CancellationToken.None); Assert.Equal(expectedName, locationInfo.Name); Assert.Equal(expectedLineOffset, locationInfo.LineOffset); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestClass() => await TestAsync("class G$$oo { }", "Goo", 0); [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668"), WorkItem(538415, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538415")] public async Task TestMethod() { await TestAsync( @"class Class { public static void Meth$$od() { } } ", "Class.Method()", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")] public async Task TestNamespace() { await TestAsync( @"namespace Namespace { class Class { void Method() { }$$ } }", "Namespace.Class.Method()", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(49000, "https://github.com/dotnet/roslyn/issues/49000")] public async Task TestFileScopedNamespace() { // This test behavior is incorrect. This should be Namespace.Class.Method. // See the associated WorkItem for details. await TestAsync( @"namespace Namespace; class Class { void Method() { }$$ } ", "Namespace.Class.Method()", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")] public async Task TestDottedNamespace() { await TestAsync( @"namespace Namespace.Another { class Class { void Method() { }$$ } }", "Namespace.Another.Class.Method()", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestNestedNamespace() { await TestAsync( @"namespace Namespace { namespace Another { class Class { void Method() { }$$ } } }", "Namespace.Another.Class.Method()", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")] public async Task TestNestedType() { await TestAsync( @"class Outer { class Inner { void Quux() {$$ } } }", "Outer.Inner.Quux()", 1); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")] public async Task TestPropertyGetter() { await TestAsync( @"class Class { string Property { get { return null;$$ } } }", "Class.Property", 4); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")] public async Task TestPropertySetter() { await TestAsync( @"class Class { string Property { get { return null; } set { string s = $$value; } } }", "Class.Property", 9); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(538415, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538415")] public async Task TestField() { await TestAsync( @"class Class { int fi$$eld; }", "Class.field", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(543494, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543494")] public async Task TestLambdaInFieldInitializer() { await TestAsync( @"class Class { Action<int> a = b => { in$$t c; }; }", "Class.a", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(543494, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543494")] public async Task TestMultipleFields() { await TestAsync( @"class Class { int a1, a$$2; }", "Class.a2", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestConstructor() { await TestAsync( @"class C1 { C1() { $$} } ", "C1.C1()", 3); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestDestructor() { await TestAsync( @"class C1 { ~C1() { $$} } ", "C1.~C1()", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestOperator() { await TestAsync( @"namespace N1 { class C1 { public static int operator +(C1 x, C1 y) { $$return 42; } } } ", "N1.C1.+(C1 x, C1 y)", 2); // Old implementation reports "operator +" (rather than "+")... } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestConversionOperator() { await TestAsync( @"namespace N1 { class C1 { public static explicit operator N1.C2(N1.C1 x) { $$return null; } } class C2 { } } ", "N1.C1.N1.C2(N1.C1 x)", 2); // Old implementation reports "explicit operator N1.C2" (rather than "N1.C2")... } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestEvent() { await TestAsync( @"class C1 { delegate void D1(); event D1 e1$$; } ", "C1.e1", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TextExplicitInterfaceImplementation() { await TestAsync( @"interface I1 { void M1(); } class C1 { void I1.M1() { $$} } ", "C1.M1()", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TextIndexer() { await TestAsync( @"class C1 { C1 this[int x] { get { $$return null; } } } ", "C1.this[int x]", 4); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestParamsParameter() { await TestAsync( @"class C1 { void M1(params int[] x) { $$ } } ", "C1.M1(params int[] x)", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestArglistParameter() { await TestAsync( @"class C1 { void M1(__arglist) { $$ } } ", "C1.M1(__arglist)", 0); // Old implementation does not show "__arglist"... } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestRefAndOutParameters() { await TestAsync( @"class C1 { void M1( ref int x, out int y ) { $$y = x; } } ", "C1.M1( ref int x, out int y )", 2); // Old implementation did not show extra spaces around the parameters... } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestOptionalParameters() { await TestAsync( @"class C1 { void M1(int x =1) { $$y = x; } } ", "C1.M1(int x =1)", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestExtensionMethod() { await TestAsync( @"static class C1 { static void M1(this int x) { }$$ } ", "C1.M1(this int x)", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestGenericType() { await TestAsync( @"class C1<T, U> { static void M1() { $$ } } ", "C1.M1()", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestGenericMethod() { await TestAsync( @"class C1<T, U> { static void M1<V>() { $$ } } ", "C1.M1()", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestGenericParameters() { await TestAsync( @"class C1<T, U> { static void M1<V>(C1<int, V> x, V y) { $$ } } ", "C1.M1(C1<int, V> x, V y)", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestMissingNamespace() { await TestAsync( @"{ class Class { int a1, a$$2; } }", "Class.a2", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestMissingNamespaceName() { await TestAsync( @"namespace { class C1 { int M1() $${ } } }", "?.C1.M1()", 1); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestMissingClassName() { await TestAsync( @"namespace N1 class { int M1() $${ } } }", "N1.M1()", 1); // Old implementation displayed "N1.?.M1", but we don't see a class declaration in the syntax tree... } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestMissingMethodName() { await TestAsync( @"namespace N1 { class C1 { static void (ref int x) { $$} } }", "N1.C1", 4); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestMissingParameterList() { await TestAsync( @"namespace N1 { class C1 { static void M1 { $$} } }", "N1.C1.M1", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TopLevelField() { await TestAsync( @"$$int f1; ", "f1", 0, new CSharpParseOptions(kind: SourceCodeKind.Script)); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TopLevelMethod() { await TestAsync( @"int M1(int x) { $$} ", "M1(int x)", 2, new CSharpParseOptions(kind: SourceCodeKind.Script)); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TopLevelStatement() { await TestAsync( @" $$System.Console.WriteLine(""Hello"") ", null, 0, new CSharpParseOptions(kind: SourceCodeKind.Script)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Debugging; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Debugging { [UseExportProvider] public class LocationInfoGetterTests { private static async Task TestAsync(string markup, string expectedName, int expectedLineOffset, CSharpParseOptions parseOptions = null) { using var workspace = TestWorkspace.CreateCSharp(markup, parseOptions); var testDocument = workspace.Documents.Single(); var position = testDocument.CursorPosition.Value; var locationInfo = await LocationInfoGetter.GetInfoAsync( workspace.CurrentSolution.Projects.Single().Documents.Single(), position, CancellationToken.None); Assert.Equal(expectedName, locationInfo.Name); Assert.Equal(expectedLineOffset, locationInfo.LineOffset); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestClass() => await TestAsync("class G$$oo { }", "Goo", 0); [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668"), WorkItem(538415, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538415")] public async Task TestMethod() { await TestAsync( @"class Class { public static void Meth$$od() { } } ", "Class.Method()", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")] public async Task TestNamespace() { await TestAsync( @"namespace Namespace { class Class { void Method() { }$$ } }", "Namespace.Class.Method()", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(49000, "https://github.com/dotnet/roslyn/issues/49000")] public async Task TestFileScopedNamespace() { // This test behavior is incorrect. This should be Namespace.Class.Method. // See the associated WorkItem for details. await TestAsync( @"namespace Namespace; class Class { void Method() { }$$ } ", "Namespace.Class.Method()", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")] public async Task TestDottedNamespace() { await TestAsync( @"namespace Namespace.Another { class Class { void Method() { }$$ } }", "Namespace.Another.Class.Method()", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestNestedNamespace() { await TestAsync( @"namespace Namespace { namespace Another { class Class { void Method() { }$$ } } }", "Namespace.Another.Class.Method()", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")] public async Task TestNestedType() { await TestAsync( @"class Outer { class Inner { void Quux() {$$ } } }", "Outer.Inner.Quux()", 1); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")] public async Task TestPropertyGetter() { await TestAsync( @"class Class { string Property { get { return null;$$ } } }", "Class.Property", 4); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")] public async Task TestPropertySetter() { await TestAsync( @"class Class { string Property { get { return null; } set { string s = $$value; } } }", "Class.Property", 9); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(538415, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538415")] public async Task TestField() { await TestAsync( @"class Class { int fi$$eld; }", "Class.field", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(543494, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543494")] public async Task TestLambdaInFieldInitializer() { await TestAsync( @"class Class { Action<int> a = b => { in$$t c; }; }", "Class.a", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(543494, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543494")] public async Task TestMultipleFields() { await TestAsync( @"class Class { int a1, a$$2; }", "Class.a2", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestConstructor() { await TestAsync( @"class C1 { C1() { $$} } ", "C1.C1()", 3); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestDestructor() { await TestAsync( @"class C1 { ~C1() { $$} } ", "C1.~C1()", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestOperator() { await TestAsync( @"namespace N1 { class C1 { public static int operator +(C1 x, C1 y) { $$return 42; } } } ", "N1.C1.+(C1 x, C1 y)", 2); // Old implementation reports "operator +" (rather than "+")... } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestConversionOperator() { await TestAsync( @"namespace N1 { class C1 { public static explicit operator N1.C2(N1.C1 x) { $$return null; } } class C2 { } } ", "N1.C1.N1.C2(N1.C1 x)", 2); // Old implementation reports "explicit operator N1.C2" (rather than "N1.C2")... } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestEvent() { await TestAsync( @"class C1 { delegate void D1(); event D1 e1$$; } ", "C1.e1", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TextExplicitInterfaceImplementation() { await TestAsync( @"interface I1 { void M1(); } class C1 { void I1.M1() { $$} } ", "C1.M1()", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TextIndexer() { await TestAsync( @"class C1 { C1 this[int x] { get { $$return null; } } } ", "C1.this[int x]", 4); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestParamsParameter() { await TestAsync( @"class C1 { void M1(params int[] x) { $$ } } ", "C1.M1(params int[] x)", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestArglistParameter() { await TestAsync( @"class C1 { void M1(__arglist) { $$ } } ", "C1.M1(__arglist)", 0); // Old implementation does not show "__arglist"... } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestRefAndOutParameters() { await TestAsync( @"class C1 { void M1( ref int x, out int y ) { $$y = x; } } ", "C1.M1( ref int x, out int y )", 2); // Old implementation did not show extra spaces around the parameters... } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestOptionalParameters() { await TestAsync( @"class C1 { void M1(int x =1) { $$y = x; } } ", "C1.M1(int x =1)", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestExtensionMethod() { await TestAsync( @"static class C1 { static void M1(this int x) { }$$ } ", "C1.M1(this int x)", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestGenericType() { await TestAsync( @"class C1<T, U> { static void M1() { $$ } } ", "C1.M1()", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestGenericMethod() { await TestAsync( @"class C1<T, U> { static void M1<V>() { $$ } } ", "C1.M1()", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestGenericParameters() { await TestAsync( @"class C1<T, U> { static void M1<V>(C1<int, V> x, V y) { $$ } } ", "C1.M1(C1<int, V> x, V y)", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestMissingNamespace() { await TestAsync( @"{ class Class { int a1, a$$2; } }", "Class.a2", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestMissingNamespaceName() { await TestAsync( @"namespace { class C1 { int M1() $${ } } }", "?.C1.M1()", 1); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestMissingClassName() { await TestAsync( @"namespace N1 class { int M1() $${ } } }", "N1.M1()", 1); // Old implementation displayed "N1.?.M1", but we don't see a class declaration in the syntax tree... } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestMissingMethodName() { await TestAsync( @"namespace N1 { class C1 { static void (ref int x) { $$} } }", "N1.C1", 4); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestMissingParameterList() { await TestAsync( @"namespace N1 { class C1 { static void M1 { $$} } }", "N1.C1.M1", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TopLevelField() { await TestAsync( @"$$int f1; ", "f1", 0, new CSharpParseOptions(kind: SourceCodeKind.Script)); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TopLevelMethod() { await TestAsync( @"int M1(int x) { $$} ", "M1(int x)", 2, new CSharpParseOptions(kind: SourceCodeKind.Script)); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TopLevelStatement() { await TestAsync( @" $$System.Console.WriteLine(""Hello"") ", null, 0, new CSharpParseOptions(kind: SourceCodeKind.Script)); } } }
1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/CodeRefactorings/MoveType/CSharpMoveTypeService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeRefactorings.MoveType; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.MoveType { [ExportLanguageService(typeof(IMoveTypeService), LanguageNames.CSharp), Shared] internal class CSharpMoveTypeService : AbstractMoveTypeService<CSharpMoveTypeService, BaseTypeDeclarationSyntax, NamespaceDeclarationSyntax, MemberDeclarationSyntax, CompilationUnitSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpMoveTypeService() { } protected override async Task<BaseTypeDeclarationSyntax> GetRelevantNodeAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken) => await document.TryGetRelevantNodeAsync<BaseTypeDeclarationSyntax>(textSpan, 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. #nullable disable using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeRefactorings.MoveType; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.MoveType { [ExportLanguageService(typeof(IMoveTypeService), LanguageNames.CSharp), Shared] internal class CSharpMoveTypeService : AbstractMoveTypeService<CSharpMoveTypeService, BaseTypeDeclarationSyntax, BaseNamespaceDeclarationSyntax, MemberDeclarationSyntax, CompilationUnitSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpMoveTypeService() { } protected override async Task<BaseTypeDeclarationSyntax> GetRelevantNodeAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken) => await document.TryGetRelevantNodeAsync<BaseTypeDeclarationSyntax>(textSpan, cancellationToken).ConfigureAwait(false); } }
1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/CodeRefactorings/SyncNamespace/CSharpChangeNamespaceService.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; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ChangeNamespace; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ChangeNamespace { [ExportLanguageService(typeof(IChangeNamespaceService), LanguageNames.CSharp), Shared] internal sealed class CSharpChangeNamespaceService : AbstractChangeNamespaceService<BaseNamespaceDeclarationSyntax, CompilationUnitSyntax, MemberDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpChangeNamespaceService() { } protected override async Task<ImmutableArray<(DocumentId, SyntaxNode)>> GetValidContainersFromAllLinkedDocumentsAsync( Document document, SyntaxNode container, CancellationToken cancellationToken) { if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles || document.IsGeneratedCode(cancellationToken)) { return default; } TextSpan containerSpan; if (container is BaseNamespaceDeclarationSyntax) { containerSpan = container.Span; } else if (container is CompilationUnitSyntax) { // A compilation unit as container means user want to move all its members from global to some namespace. // We use an empty span to indicate this case. containerSpan = default; } else { throw ExceptionUtilities.Unreachable; } if (!IsSupportedLinkedDocument(document, out var allDocumentIds)) return default; return await TryGetApplicableContainersFromAllDocumentsAsync( document.Project.Solution, allDocumentIds, containerSpan, cancellationToken).ConfigureAwait(false); } protected override string GetDeclaredNamespace(SyntaxNode container) { if (container is CompilationUnitSyntax) return string.Empty; if (container is BaseNamespaceDeclarationSyntax namespaceDecl) return CSharpSyntaxGenerator.Instance.GetName(namespaceDecl); throw ExceptionUtilities.Unreachable; } protected override SyntaxList<MemberDeclarationSyntax> GetMemberDeclarationsInContainer(SyntaxNode container) { if (container is BaseNamespaceDeclarationSyntax namespaceDecl) return namespaceDecl.Members; if (container is CompilationUnitSyntax compilationUnit) return compilationUnit.Members; throw ExceptionUtilities.Unreachable; } /// <summary> /// Try to get a new node to replace given node, which is a reference to a top-level type declared inside the namespace to be changed. /// If this reference is the right side of a qualified name, the new node returned would be the entire qualified name. Depends on /// whether <paramref name="newNamespaceParts"/> is provided, the name in the new node might be qualified with this new namespace instead. /// </summary> /// <param name="reference">A reference to a type declared inside the namespace to be changed, which is calculated based on results from /// `SymbolFinder.FindReferencesAsync`.</param> /// <param name="newNamespaceParts">If specified, and the reference is qualified with namespace, the namespace part of original reference /// will be replaced with given namespace in the new node.</param> /// <param name="oldNode">The node to be replaced. This might be an ancestor of original reference.</param> /// <param name="newNode">The replacement node.</param> public override bool TryGetReplacementReferenceSyntax( SyntaxNode reference, ImmutableArray<string> newNamespaceParts, ISyntaxFactsService syntaxFacts, [NotNullWhen(returnValue: true)] out SyntaxNode? oldNode, [NotNullWhen(returnValue: true)] out SyntaxNode? newNode) { if (reference is not SimpleNameSyntax nameRef) { oldNode = newNode = null; return false; } // A few different cases are handled here: // // 1. When the reference is not qualified (i.e. just a simple name), then there's nothing need to be done. // And both old and new will point to the original reference. // // 2. When the new namespace is not specified, we don't need to change the qualified part of reference. // Both old and new will point to the qualified reference. // // 3. When the new namespace is "", i.e. we are moving type referenced by name here to global namespace. // As a result, we need replace qualified reference with the simple name. // // 4. When the namespace is specified and not "", i.e. we are moving referenced type to a different non-global // namespace. We need to replace the qualified reference with a new qualified reference (which is qualified // with new namespace.) // // Note that qualified type name can appear in QualifiedNameSyntax or MemberAccessSyntax, so we need to handle both cases. if (syntaxFacts.IsRightSideOfQualifiedName(nameRef)) { RoslynDebug.Assert(nameRef.Parent is object); oldNode = nameRef.Parent; var aliasQualifier = GetAliasQualifier(oldNode); if (!TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode)) { var qualifiedNamespaceName = CreateNamespaceAsQualifiedName(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1); newNode = SyntaxFactory.QualifiedName(qualifiedNamespaceName, nameRef.WithoutTrivia()); } // We might lose some trivia associated with children of `oldNode`. newNode = newNode.WithTriviaFrom(oldNode); return true; } else if (syntaxFacts.IsNameOfSimpleMemberAccessExpression(nameRef) || syntaxFacts.IsNameOfMemberBindingExpression(nameRef)) { RoslynDebug.Assert(nameRef.Parent is object); oldNode = nameRef.Parent; var aliasQualifier = GetAliasQualifier(oldNode); if (!TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode)) { var memberAccessNamespaceName = CreateNamespaceAsMemberAccess(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1); newNode = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, memberAccessNamespaceName, nameRef.WithoutTrivia()); } // We might lose some trivia associated with children of `oldNode`. newNode = newNode.WithTriviaFrom(oldNode); return true; } else if (nameRef.Parent is NameMemberCrefSyntax crefName && crefName.Parent is QualifiedCrefSyntax qualifiedCref) { // This is the case where the reference is the right most part of a qualified name in `cref`. // for example, `<see cref="Foo.Baz.Bar"/>` and `<see cref="SomeAlias::Foo.Baz.Bar"/>`. // This is the form of `cref` we need to handle as a spacial case when changing namespace name or // changing namespace from non-global to global, other cases in these 2 scenarios can be handled in the // same way we handle non cref references, for example, `<see cref="SomeAlias::Foo"/>` and `<see cref="Foo"/>`. var container = qualifiedCref.Container; var aliasQualifier = GetAliasQualifier(container); if (TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode)) { // We will replace entire `QualifiedCrefSyntax` with a `TypeCrefSyntax`, // which is a alias qualified simple name, similar to the regular case above. oldNode = qualifiedCref; newNode = SyntaxFactory.TypeCref((AliasQualifiedNameSyntax)newNode!); } else { // if the new namespace is not global, then we just need to change the container in `QualifiedCrefSyntax`, // which is just a regular namespace node, no cref node involve here. oldNode = container; newNode = CreateNamespaceAsQualifiedName(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1); } return true; } // Simple name reference, nothing to be done. // The name will be resolved by adding proper import. oldNode = newNode = nameRef; return false; } private static bool TryGetGlobalQualifiedName( ImmutableArray<string> newNamespaceParts, SimpleNameSyntax nameNode, string? aliasQualifier, [NotNullWhen(returnValue: true)] out SyntaxNode? newNode) { if (IsGlobalNamespace(newNamespaceParts)) { // If new namespace is "", then name will be declared in global namespace. // We will replace qualified reference with simple name qualified with alias (global if it's not alias qualified) var aliasNode = aliasQualifier?.ToIdentifierName() ?? SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)); newNode = SyntaxFactory.AliasQualifiedName(aliasNode, nameNode.WithoutTrivia()); return true; } newNode = null; return false; } /// <summary> /// Try to change the namespace declaration based on the following rules: /// - if neither declared nor target namespace are "" (i.e. global namespace), /// then we try to change the name of the namespace. /// - if declared namespace is "", then we try to move all types declared /// in global namespace in the document into a new namespace declaration. /// - if target namespace is "", then we try to move all members in declared /// namespace to global namespace (i.e. remove the namespace declaration). /// </summary> protected override CompilationUnitSyntax ChangeNamespaceDeclaration( CompilationUnitSyntax root, ImmutableArray<string> declaredNamespaceParts, ImmutableArray<string> targetNamespaceParts) { Debug.Assert(!declaredNamespaceParts.IsDefault && !targetNamespaceParts.IsDefault); var container = root.GetAnnotatedNodes(ContainerAnnotation).Single(); if (container is CompilationUnitSyntax compilationUnit) { // Move everything from global namespace to a namespace declaration Debug.Assert(IsGlobalNamespace(declaredNamespaceParts)); return MoveMembersFromGlobalToNamespace(compilationUnit, targetNamespaceParts); } if (container is BaseNamespaceDeclarationSyntax namespaceDecl) { // Move everything to global namespace if (IsGlobalNamespace(targetNamespaceParts)) return MoveMembersFromNamespaceToGlobal(root, namespaceDecl); // Change namespace name return root.ReplaceNode( namespaceDecl, namespaceDecl.WithName( CreateNamespaceAsQualifiedName(targetNamespaceParts, aliasQualifier: null, targetNamespaceParts.Length - 1) .WithTriviaFrom(namespaceDecl.Name).WithAdditionalAnnotations(WarningAnnotation)) .WithoutAnnotations(ContainerAnnotation)); // Make sure to remove the annotation we added } throw ExceptionUtilities.Unreachable; } private static CompilationUnitSyntax MoveMembersFromNamespaceToGlobal( CompilationUnitSyntax root, BaseNamespaceDeclarationSyntax namespaceDecl) { var (namespaceOpeningTrivia, namespaceClosingTrivia) = GetOpeningAndClosingTriviaOfNamespaceDeclaration(namespaceDecl); var members = namespaceDecl.Members; var eofToken = root.EndOfFileToken .WithAdditionalAnnotations(WarningAnnotation); // Try to preserve trivia from original namespace declaration. // If there's any member inside the declaration, we attach them to the // first and last member, otherwise, simply attach all to the EOF token. if (members.Count > 0) { var first = members.First(); var firstWithTrivia = first.WithPrependedLeadingTrivia(namespaceOpeningTrivia); members = members.Replace(first, firstWithTrivia); var last = members.Last(); var lastWithTrivia = last.WithAppendedTrailingTrivia(namespaceClosingTrivia); members = members.Replace(last, lastWithTrivia); } else { eofToken = eofToken.WithPrependedLeadingTrivia( namespaceOpeningTrivia.Concat(namespaceClosingTrivia)); } // Moving inner imports out of the namespace declaration can lead to a break in semantics. // For example: // // namespace A.B.C // { // using D.E.F; // } // // The using of D.E.F is looked up with in the context of A.B.C first. If it's moved outside, // it may fail to resolve. return root.Update( root.Externs.AddRange(namespaceDecl.Externs), root.Usings.AddRange(namespaceDecl.Usings), root.AttributeLists, root.Members.ReplaceRange(namespaceDecl, members), eofToken); } private static CompilationUnitSyntax MoveMembersFromGlobalToNamespace(CompilationUnitSyntax compilationUnit, ImmutableArray<string> targetNamespaceParts) { Debug.Assert(!compilationUnit.Members.Any(m => m is BaseNamespaceDeclarationSyntax)); var targetNamespaceDecl = SyntaxFactory.NamespaceDeclaration( name: CreateNamespaceAsQualifiedName(targetNamespaceParts, aliasQualifier: null, targetNamespaceParts.Length - 1) .WithAdditionalAnnotations(WarningAnnotation), externs: default, usings: default, members: compilationUnit.Members); return compilationUnit.WithMembers(new SyntaxList<MemberDeclarationSyntax>(targetNamespaceDecl)) .WithoutAnnotations(ContainerAnnotation); // Make sure to remove the annotation we added } /// <summary> /// For the node specified by <paramref name="span"/> to be applicable container, it must be a namespace /// declaration or a compilation unit, contain no partial declarations and meet the following additional /// requirements: /// /// - If a namespace declaration: /// 1. It doesn't contain or is nested in other namespace declarations /// 2. The name of the namespace is valid (i.e. no errors) /// /// - If a compilation unit (i.e. <paramref name="span"/> is empty), there must be no namespace declaration /// inside (i.e. all members are declared in global namespace) /// </summary> protected override async Task<SyntaxNode?> TryGetApplicableContainerFromSpanAsync(Document document, TextSpan span, CancellationToken cancellationToken) { var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(syntaxRoot); var compilationUnit = (CompilationUnitSyntax)syntaxRoot; SyntaxNode? container = null; // Empty span means that user wants to move all types declared in the document to a new namespace. // This action is only supported when everything in the document is declared in global namespace, // which we use the number of namespace declaration nodes to decide. if (span.IsEmpty) { if (ContainsNamespaceDeclaration(compilationUnit)) return null; container = compilationUnit; } else { // Otherwise, the span should contain a namespace declaration node, which must be the only one // in the entire syntax spine to enable the change namespace operation. if (!compilationUnit.Span.Contains(span)) return null; var node = compilationUnit.FindNode(span, getInnermostNodeForTie: true); var namespaceDecl = node.AncestorsAndSelf().OfType<BaseNamespaceDeclarationSyntax>().SingleOrDefault(); if (namespaceDecl == null) return null; if (namespaceDecl.Name.GetDiagnostics().Any(diag => diag.DefaultSeverity == DiagnosticSeverity.Error)) return null; if (ContainsNamespaceDeclaration(node)) return null; container = namespaceDecl; } var containsPartial = await ContainsPartialTypeWithMultipleDeclarationsAsync(document, container, cancellationToken).ConfigureAwait(false); if (containsPartial) return null; return container; static bool ContainsNamespaceDeclaration(SyntaxNode node) => node.DescendantNodes(n => n is CompilationUnitSyntax || n is BaseNamespaceDeclarationSyntax) .OfType<BaseNamespaceDeclarationSyntax>().Any(); } private static string? GetAliasQualifier(SyntaxNode? name) { while (true) { switch (name) { case QualifiedNameSyntax qualifiedNameNode: name = qualifiedNameNode.Left; continue; case MemberAccessExpressionSyntax memberAccessNode: name = memberAccessNode.Expression; continue; case AliasQualifiedNameSyntax aliasQualifiedNameNode: return aliasQualifiedNameNode.Alias.Identifier.ValueText; } return null; } } private static NameSyntax CreateNamespaceAsQualifiedName(ImmutableArray<string> namespaceParts, string? aliasQualifier, int index) { var part = namespaceParts[index].EscapeIdentifier(); Debug.Assert(part.Length > 0); var namePiece = SyntaxFactory.IdentifierName(part); if (index == 0) return aliasQualifier == null ? namePiece : SyntaxFactory.AliasQualifiedName(aliasQualifier, namePiece); return SyntaxFactory.QualifiedName(CreateNamespaceAsQualifiedName(namespaceParts, aliasQualifier, index - 1), namePiece); } private static ExpressionSyntax CreateNamespaceAsMemberAccess(ImmutableArray<string> namespaceParts, string? aliasQualifier, int index) { var part = namespaceParts[index].EscapeIdentifier(); Debug.Assert(part.Length > 0); var namePiece = SyntaxFactory.IdentifierName(part); if (index == 0) { return aliasQualifier == null ? (NameSyntax)namePiece : SyntaxFactory.AliasQualifiedName(aliasQualifier, namePiece); } return SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, CreateNamespaceAsMemberAccess(namespaceParts, aliasQualifier, index - 1), namePiece); } /// <summary> /// return trivia attached to namespace declaration. /// Leading trivia of the node and trivia around opening brace, as well as /// trivia around closing brace are concatenated together respectively. /// </summary> private static (ImmutableArray<SyntaxTrivia> openingTrivia, ImmutableArray<SyntaxTrivia> closingTrivia) GetOpeningAndClosingTriviaOfNamespaceDeclaration(BaseNamespaceDeclarationSyntax baseNamespace) { var openingBuilder = ArrayBuilder<SyntaxTrivia>.GetInstance(); var closingBuilder = ArrayBuilder<SyntaxTrivia>.GetInstance(); openingBuilder.AddRange(baseNamespace.GetLeadingTrivia()); if (baseNamespace is NamespaceDeclarationSyntax namespaceDeclaration) { openingBuilder.AddRange(namespaceDeclaration.OpenBraceToken.LeadingTrivia); openingBuilder.AddRange(namespaceDeclaration.OpenBraceToken.TrailingTrivia); closingBuilder.AddRange(namespaceDeclaration.CloseBraceToken.LeadingTrivia); closingBuilder.AddRange(namespaceDeclaration.CloseBraceToken.TrailingTrivia); } else if (baseNamespace is FileScopedNamespaceDeclarationSyntax fileScopedNamespace) { openingBuilder.AddRange(fileScopedNamespace.SemicolonToken.TrailingTrivia); } return (openingBuilder.ToImmutableAndFree(), closingBuilder.ToImmutableAndFree()); } } }
// Licensed to the .NET Foundation under one or more 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; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ChangeNamespace; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ChangeNamespace { [ExportLanguageService(typeof(IChangeNamespaceService), LanguageNames.CSharp), Shared] internal sealed class CSharpChangeNamespaceService : AbstractChangeNamespaceService<BaseNamespaceDeclarationSyntax, CompilationUnitSyntax, MemberDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpChangeNamespaceService() { } protected override async Task<ImmutableArray<(DocumentId, SyntaxNode)>> GetValidContainersFromAllLinkedDocumentsAsync( Document document, SyntaxNode container, CancellationToken cancellationToken) { if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles || document.IsGeneratedCode(cancellationToken)) { return default; } TextSpan containerSpan; if (container is BaseNamespaceDeclarationSyntax) { containerSpan = container.Span; } else if (container is CompilationUnitSyntax) { // A compilation unit as container means user want to move all its members from global to some namespace. // We use an empty span to indicate this case. containerSpan = default; } else { throw ExceptionUtilities.Unreachable; } if (!IsSupportedLinkedDocument(document, out var allDocumentIds)) return default; return await TryGetApplicableContainersFromAllDocumentsAsync( document.Project.Solution, allDocumentIds, containerSpan, cancellationToken).ConfigureAwait(false); } protected override string GetDeclaredNamespace(SyntaxNode container) { if (container is CompilationUnitSyntax) return string.Empty; if (container is BaseNamespaceDeclarationSyntax namespaceDecl) return CSharpSyntaxGenerator.Instance.GetName(namespaceDecl); throw ExceptionUtilities.Unreachable; } protected override SyntaxList<MemberDeclarationSyntax> GetMemberDeclarationsInContainer(SyntaxNode container) { if (container is BaseNamespaceDeclarationSyntax namespaceDecl) return namespaceDecl.Members; if (container is CompilationUnitSyntax compilationUnit) return compilationUnit.Members; throw ExceptionUtilities.Unreachable; } /// <summary> /// Try to get a new node to replace given node, which is a reference to a top-level type declared inside the namespace to be changed. /// If this reference is the right side of a qualified name, the new node returned would be the entire qualified name. Depends on /// whether <paramref name="newNamespaceParts"/> is provided, the name in the new node might be qualified with this new namespace instead. /// </summary> /// <param name="reference">A reference to a type declared inside the namespace to be changed, which is calculated based on results from /// `SymbolFinder.FindReferencesAsync`.</param> /// <param name="newNamespaceParts">If specified, and the reference is qualified with namespace, the namespace part of original reference /// will be replaced with given namespace in the new node.</param> /// <param name="oldNode">The node to be replaced. This might be an ancestor of original reference.</param> /// <param name="newNode">The replacement node.</param> public override bool TryGetReplacementReferenceSyntax( SyntaxNode reference, ImmutableArray<string> newNamespaceParts, ISyntaxFactsService syntaxFacts, [NotNullWhen(returnValue: true)] out SyntaxNode? oldNode, [NotNullWhen(returnValue: true)] out SyntaxNode? newNode) { if (reference is not SimpleNameSyntax nameRef) { oldNode = newNode = null; return false; } // A few different cases are handled here: // // 1. When the reference is not qualified (i.e. just a simple name), then there's nothing need to be done. // And both old and new will point to the original reference. // // 2. When the new namespace is not specified, we don't need to change the qualified part of reference. // Both old and new will point to the qualified reference. // // 3. When the new namespace is "", i.e. we are moving type referenced by name here to global namespace. // As a result, we need replace qualified reference with the simple name. // // 4. When the namespace is specified and not "", i.e. we are moving referenced type to a different non-global // namespace. We need to replace the qualified reference with a new qualified reference (which is qualified // with new namespace.) // // Note that qualified type name can appear in QualifiedNameSyntax or MemberAccessSyntax, so we need to handle both cases. if (syntaxFacts.IsRightSideOfQualifiedName(nameRef)) { RoslynDebug.Assert(nameRef.Parent is object); oldNode = nameRef.Parent; var aliasQualifier = GetAliasQualifier(oldNode); if (!TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode)) { var qualifiedNamespaceName = CreateNamespaceAsQualifiedName(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1); newNode = SyntaxFactory.QualifiedName(qualifiedNamespaceName, nameRef.WithoutTrivia()); } // We might lose some trivia associated with children of `oldNode`. newNode = newNode.WithTriviaFrom(oldNode); return true; } else if (syntaxFacts.IsNameOfSimpleMemberAccessExpression(nameRef) || syntaxFacts.IsNameOfMemberBindingExpression(nameRef)) { RoslynDebug.Assert(nameRef.Parent is object); oldNode = nameRef.Parent; var aliasQualifier = GetAliasQualifier(oldNode); if (!TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode)) { var memberAccessNamespaceName = CreateNamespaceAsMemberAccess(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1); newNode = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, memberAccessNamespaceName, nameRef.WithoutTrivia()); } // We might lose some trivia associated with children of `oldNode`. newNode = newNode.WithTriviaFrom(oldNode); return true; } else if (nameRef.Parent is NameMemberCrefSyntax crefName && crefName.Parent is QualifiedCrefSyntax qualifiedCref) { // This is the case where the reference is the right most part of a qualified name in `cref`. // for example, `<see cref="Foo.Baz.Bar"/>` and `<see cref="SomeAlias::Foo.Baz.Bar"/>`. // This is the form of `cref` we need to handle as a spacial case when changing namespace name or // changing namespace from non-global to global, other cases in these 2 scenarios can be handled in the // same way we handle non cref references, for example, `<see cref="SomeAlias::Foo"/>` and `<see cref="Foo"/>`. var container = qualifiedCref.Container; var aliasQualifier = GetAliasQualifier(container); if (TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode)) { // We will replace entire `QualifiedCrefSyntax` with a `TypeCrefSyntax`, // which is a alias qualified simple name, similar to the regular case above. oldNode = qualifiedCref; newNode = SyntaxFactory.TypeCref((AliasQualifiedNameSyntax)newNode!); } else { // if the new namespace is not global, then we just need to change the container in `QualifiedCrefSyntax`, // which is just a regular namespace node, no cref node involve here. oldNode = container; newNode = CreateNamespaceAsQualifiedName(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1); } return true; } // Simple name reference, nothing to be done. // The name will be resolved by adding proper import. oldNode = newNode = nameRef; return false; } private static bool TryGetGlobalQualifiedName( ImmutableArray<string> newNamespaceParts, SimpleNameSyntax nameNode, string? aliasQualifier, [NotNullWhen(returnValue: true)] out SyntaxNode? newNode) { if (IsGlobalNamespace(newNamespaceParts)) { // If new namespace is "", then name will be declared in global namespace. // We will replace qualified reference with simple name qualified with alias (global if it's not alias qualified) var aliasNode = aliasQualifier?.ToIdentifierName() ?? SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)); newNode = SyntaxFactory.AliasQualifiedName(aliasNode, nameNode.WithoutTrivia()); return true; } newNode = null; return false; } /// <summary> /// Try to change the namespace declaration based on the following rules: /// - if neither declared nor target namespace are "" (i.e. global namespace), /// then we try to change the name of the namespace. /// - if declared namespace is "", then we try to move all types declared /// in global namespace in the document into a new namespace declaration. /// - if target namespace is "", then we try to move all members in declared /// namespace to global namespace (i.e. remove the namespace declaration). /// </summary> protected override CompilationUnitSyntax ChangeNamespaceDeclaration( CompilationUnitSyntax root, ImmutableArray<string> declaredNamespaceParts, ImmutableArray<string> targetNamespaceParts) { Debug.Assert(!declaredNamespaceParts.IsDefault && !targetNamespaceParts.IsDefault); var container = root.GetAnnotatedNodes(ContainerAnnotation).Single(); if (container is CompilationUnitSyntax compilationUnit) { // Move everything from global namespace to a namespace declaration Debug.Assert(IsGlobalNamespace(declaredNamespaceParts)); return MoveMembersFromGlobalToNamespace(compilationUnit, targetNamespaceParts); } if (container is BaseNamespaceDeclarationSyntax namespaceDecl) { // Move everything to global namespace if (IsGlobalNamespace(targetNamespaceParts)) return MoveMembersFromNamespaceToGlobal(root, namespaceDecl); // Change namespace name return root.ReplaceNode( namespaceDecl, namespaceDecl.WithName( CreateNamespaceAsQualifiedName(targetNamespaceParts, aliasQualifier: null, targetNamespaceParts.Length - 1) .WithTriviaFrom(namespaceDecl.Name).WithAdditionalAnnotations(WarningAnnotation)) .WithoutAnnotations(ContainerAnnotation)); // Make sure to remove the annotation we added } throw ExceptionUtilities.Unreachable; } private static CompilationUnitSyntax MoveMembersFromNamespaceToGlobal( CompilationUnitSyntax root, BaseNamespaceDeclarationSyntax namespaceDecl) { var (namespaceOpeningTrivia, namespaceClosingTrivia) = GetOpeningAndClosingTriviaOfNamespaceDeclaration(namespaceDecl); var members = namespaceDecl.Members; var eofToken = root.EndOfFileToken .WithAdditionalAnnotations(WarningAnnotation); // Try to preserve trivia from original namespace declaration. // If there's any member inside the declaration, we attach them to the // first and last member, otherwise, simply attach all to the EOF token. if (members.Count > 0) { var first = members.First(); var firstWithTrivia = first.WithPrependedLeadingTrivia(namespaceOpeningTrivia); members = members.Replace(first, firstWithTrivia); var last = members.Last(); var lastWithTrivia = last.WithAppendedTrailingTrivia(namespaceClosingTrivia); members = members.Replace(last, lastWithTrivia); } else { eofToken = eofToken.WithPrependedLeadingTrivia( namespaceOpeningTrivia.Concat(namespaceClosingTrivia)); } // Moving inner imports out of the namespace declaration can lead to a break in semantics. // For example: // // namespace A.B.C // { // using D.E.F; // } // // The using of D.E.F is looked up with in the context of A.B.C first. If it's moved outside, // it may fail to resolve. return root.Update( root.Externs.AddRange(namespaceDecl.Externs), root.Usings.AddRange(namespaceDecl.Usings), root.AttributeLists, root.Members.ReplaceRange(namespaceDecl, members), eofToken); } private static CompilationUnitSyntax MoveMembersFromGlobalToNamespace(CompilationUnitSyntax compilationUnit, ImmutableArray<string> targetNamespaceParts) { Debug.Assert(!compilationUnit.Members.Any(m => m is BaseNamespaceDeclarationSyntax)); var targetNamespaceDecl = SyntaxFactory.NamespaceDeclaration( name: CreateNamespaceAsQualifiedName(targetNamespaceParts, aliasQualifier: null, targetNamespaceParts.Length - 1) .WithAdditionalAnnotations(WarningAnnotation), externs: default, usings: default, members: compilationUnit.Members); return compilationUnit.WithMembers(new SyntaxList<MemberDeclarationSyntax>(targetNamespaceDecl)) .WithoutAnnotations(ContainerAnnotation); // Make sure to remove the annotation we added } /// <summary> /// For the node specified by <paramref name="span"/> to be applicable container, it must be a namespace /// declaration or a compilation unit, contain no partial declarations and meet the following additional /// requirements: /// /// - If a namespace declaration: /// 1. It doesn't contain or is nested in other namespace declarations /// 2. The name of the namespace is valid (i.e. no errors) /// /// - If a compilation unit (i.e. <paramref name="span"/> is empty), there must be no namespace declaration /// inside (i.e. all members are declared in global namespace) /// </summary> protected override async Task<SyntaxNode?> TryGetApplicableContainerFromSpanAsync(Document document, TextSpan span, CancellationToken cancellationToken) { var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(syntaxRoot); var compilationUnit = (CompilationUnitSyntax)syntaxRoot; SyntaxNode? container = null; // Empty span means that user wants to move all types declared in the document to a new namespace. // This action is only supported when everything in the document is declared in global namespace, // which we use the number of namespace declaration nodes to decide. if (span.IsEmpty) { if (ContainsNamespaceDeclaration(compilationUnit)) return null; container = compilationUnit; } else { // Otherwise, the span should contain a namespace declaration node, which must be the only one // in the entire syntax spine to enable the change namespace operation. if (!compilationUnit.Span.Contains(span)) return null; var node = compilationUnit.FindNode(span, getInnermostNodeForTie: true); var namespaceDecl = node.AncestorsAndSelf().OfType<BaseNamespaceDeclarationSyntax>().SingleOrDefault(); if (namespaceDecl == null) return null; if (namespaceDecl.Name.GetDiagnostics().Any(diag => diag.DefaultSeverity == DiagnosticSeverity.Error)) return null; if (ContainsNamespaceDeclaration(node)) return null; container = namespaceDecl; } var containsPartial = await ContainsPartialTypeWithMultipleDeclarationsAsync(document, container, cancellationToken).ConfigureAwait(false); if (containsPartial) return null; return container; static bool ContainsNamespaceDeclaration(SyntaxNode node) => node.DescendantNodes(n => n is CompilationUnitSyntax || n is BaseNamespaceDeclarationSyntax) .OfType<BaseNamespaceDeclarationSyntax>().Any(); } private static string? GetAliasQualifier(SyntaxNode? name) { while (true) { switch (name) { case QualifiedNameSyntax qualifiedNameNode: name = qualifiedNameNode.Left; continue; case MemberAccessExpressionSyntax memberAccessNode: name = memberAccessNode.Expression; continue; case AliasQualifiedNameSyntax aliasQualifiedNameNode: return aliasQualifiedNameNode.Alias.Identifier.ValueText; } return null; } } private static NameSyntax CreateNamespaceAsQualifiedName(ImmutableArray<string> namespaceParts, string? aliasQualifier, int index) { var part = namespaceParts[index].EscapeIdentifier(); Debug.Assert(part.Length > 0); var namePiece = SyntaxFactory.IdentifierName(part); if (index == 0) return aliasQualifier == null ? namePiece : SyntaxFactory.AliasQualifiedName(aliasQualifier, namePiece); return SyntaxFactory.QualifiedName(CreateNamespaceAsQualifiedName(namespaceParts, aliasQualifier, index - 1), namePiece); } private static ExpressionSyntax CreateNamespaceAsMemberAccess(ImmutableArray<string> namespaceParts, string? aliasQualifier, int index) { var part = namespaceParts[index].EscapeIdentifier(); Debug.Assert(part.Length > 0); var namePiece = SyntaxFactory.IdentifierName(part); if (index == 0) { return aliasQualifier == null ? (NameSyntax)namePiece : SyntaxFactory.AliasQualifiedName(aliasQualifier, namePiece); } return SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, CreateNamespaceAsMemberAccess(namespaceParts, aliasQualifier, index - 1), namePiece); } /// <summary> /// return trivia attached to namespace declaration. /// Leading trivia of the node and trivia around opening brace, as well as /// trivia around closing brace are concatenated together respectively. /// </summary> private static (ImmutableArray<SyntaxTrivia> openingTrivia, ImmutableArray<SyntaxTrivia> closingTrivia) GetOpeningAndClosingTriviaOfNamespaceDeclaration(BaseNamespaceDeclarationSyntax baseNamespace) { var openingBuilder = ArrayBuilder<SyntaxTrivia>.GetInstance(); var closingBuilder = ArrayBuilder<SyntaxTrivia>.GetInstance(); openingBuilder.AddRange(baseNamespace.GetLeadingTrivia()); if (baseNamespace is NamespaceDeclarationSyntax namespaceDeclaration) { openingBuilder.AddRange(namespaceDeclaration.OpenBraceToken.LeadingTrivia); openingBuilder.AddRange(namespaceDeclaration.OpenBraceToken.TrailingTrivia); closingBuilder.AddRange(namespaceDeclaration.CloseBraceToken.LeadingTrivia); closingBuilder.AddRange(namespaceDeclaration.CloseBraceToken.TrailingTrivia); } else if (baseNamespace is FileScopedNamespaceDeclarationSyntax fileScopedNamespace) { openingBuilder.AddRange(fileScopedNamespace.SemicolonToken.TrailingTrivia); } return (openingBuilder.ToImmutableAndFree(), closingBuilder.ToImmutableAndFree()); } } }
1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/SyntaxFacts/CSharpSyntaxFacts.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Shared.Extensions; #if CODE_STYLE using Microsoft.CodeAnalysis.Internal.Editing; #else using Microsoft.CodeAnalysis.Editing; #endif namespace Microsoft.CodeAnalysis.CSharp.LanguageServices { internal class CSharpSyntaxFacts : AbstractSyntaxFacts, ISyntaxFacts { internal static readonly CSharpSyntaxFacts Instance = new(); protected CSharpSyntaxFacts() { } public bool IsCaseSensitive => true; public StringComparer StringComparer { get; } = StringComparer.Ordinal; public SyntaxTrivia ElasticMarker => SyntaxFactory.ElasticMarker; public SyntaxTrivia ElasticCarriageReturnLineFeed => SyntaxFactory.ElasticCarriageReturnLineFeed; public override ISyntaxKinds SyntaxKinds { get; } = CSharpSyntaxKinds.Instance; protected override IDocumentationCommentService DocumentationCommentService => CSharpDocumentationCommentService.Instance; public bool SupportsIndexingInitializer(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp6; public bool SupportsThrowExpression(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7; public bool SupportsLocalFunctionDeclaration(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7; public bool SupportsRecord(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp9; public bool SupportsRecordStruct(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion.IsCSharp10OrAbove(); public SyntaxToken ParseToken(string text) => SyntaxFactory.ParseToken(text); public SyntaxTriviaList ParseLeadingTrivia(string text) => SyntaxFactory.ParseLeadingTrivia(text); public string EscapeIdentifier(string identifier) { var nullIndex = identifier.IndexOf('\0'); if (nullIndex >= 0) { identifier = identifier.Substring(0, nullIndex); } var needsEscaping = SyntaxFacts.GetKeywordKind(identifier) != SyntaxKind.None; return needsEscaping ? "@" + identifier : identifier; } public bool IsVerbatimIdentifier(SyntaxToken token) => token.IsVerbatimIdentifier(); public bool IsOperator(SyntaxToken token) { var kind = token.Kind(); return (SyntaxFacts.IsAnyUnaryExpression(kind) && (token.Parent is PrefixUnaryExpressionSyntax || token.Parent is PostfixUnaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) || (SyntaxFacts.IsBinaryExpression(kind) && (token.Parent is BinaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) || (SyntaxFacts.IsAssignmentExpressionOperatorToken(kind) && token.Parent is AssignmentExpressionSyntax); } public bool IsReservedKeyword(SyntaxToken token) => SyntaxFacts.IsReservedKeyword(token.Kind()); public bool IsContextualKeyword(SyntaxToken token) => SyntaxFacts.IsContextualKeyword(token.Kind()); public bool IsPreprocessorKeyword(SyntaxToken token) => SyntaxFacts.IsPreprocessorKeyword(token.Kind()); public bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) => syntaxTree.IsPreProcessorDirectiveContext( position, syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true), cancellationToken); public bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken) { if (syntaxTree == null) { return false; } return syntaxTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken); } public bool IsDirective([NotNullWhen(true)] SyntaxNode? node) => node is DirectiveTriviaSyntax; public bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? node, out ExternalSourceInfo info) { if (node is LineDirectiveTriviaSyntax lineDirective) { if (lineDirective.Line.Kind() == SyntaxKind.DefaultKeyword) { info = new ExternalSourceInfo(null, ends: true); return true; } else if (lineDirective.Line.Kind() == SyntaxKind.NumericLiteralToken && lineDirective.Line.Value is int) { info = new ExternalSourceInfo((int)lineDirective.Line.Value, false); return true; } } info = default; return false; } public bool IsRightSideOfQualifiedName([NotNullWhen(true)] SyntaxNode? node) { var name = node as SimpleNameSyntax; return name.IsRightSideOfQualifiedName(); } public bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) { var name = node as SimpleNameSyntax; return name.IsSimpleMemberAccessExpressionName(); } public bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) => node?.Parent is MemberAccessExpressionSyntax memberAccess && memberAccess.Name == node; public bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node) { var name = node as SimpleNameSyntax; return name.IsMemberBindingExpressionName(); } [return: NotNullIfNotNull("node")] public SyntaxNode? GetStandaloneExpression(SyntaxNode? node) => node is ExpressionSyntax expression ? SyntaxFactory.GetStandaloneExpression(expression) : node; public SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node) => node.GetRootConditionalAccessExpression(); public bool IsObjectCreationExpressionType([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.ObjectCreationExpression, out ObjectCreationExpressionSyntax? objectCreation) && objectCreation.Type == node; public bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node) => node is DeclarationExpressionSyntax; public bool IsAttributeName(SyntaxNode node) => SyntaxFacts.IsAttributeName(node); public bool IsAnonymousFunction([NotNullWhen(true)] SyntaxNode? node) { return node is ParenthesizedLambdaExpressionSyntax || node is SimpleLambdaExpressionSyntax || node is AnonymousMethodExpressionSyntax; } public bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node) => node is ArgumentSyntax arg && arg.NameColon != null; public bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node) => node.CheckParent<NameColonSyntax>(p => p.Name == node); public SyntaxToken? GetNameOfParameter(SyntaxNode? node) => (node as ParameterSyntax)?.Identifier; public SyntaxNode? GetDefaultOfParameter(SyntaxNode? node) => (node as ParameterSyntax)?.Default; public SyntaxNode? GetParameterList(SyntaxNode node) => node.GetParameterList(); public bool IsParameterList([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ParameterList, SyntaxKind.BracketedParameterList); public SyntaxToken GetIdentifierOfGenericName(SyntaxNode? genericName) { return genericName is GenericNameSyntax csharpGenericName ? csharpGenericName.Identifier : default; } public bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.UsingDirective, out UsingDirectiveSyntax? usingDirective) && usingDirective.Name == node; public bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node) => node is UsingDirectiveSyntax usingDirectiveNode && usingDirectiveNode.Alias != null; public bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node) => node is ForEachVariableStatementSyntax; public bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node) => node is AssignmentExpressionSyntax assignment && assignment.IsDeconstruction(); public Location GetDeconstructionReferenceLocation(SyntaxNode node) { return node switch { AssignmentExpressionSyntax assignment => assignment.Left.GetLocation(), ForEachVariableStatementSyntax @foreach => @foreach.Variable.GetLocation(), _ => throw ExceptionUtilities.UnexpectedValue(node.Kind()), }; } public bool IsStatement([NotNullWhen(true)] SyntaxNode? node) => node is StatementSyntax; public bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node) => node is StatementSyntax; public bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node) { if (node is BlockSyntax || node is ArrowExpressionClauseSyntax) { return node.Parent is BaseMethodDeclarationSyntax || node.Parent is AccessorDeclarationSyntax; } return false; } public SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode? node) => (node as ReturnStatementSyntax)?.Expression; public bool IsThisConstructorInitializer(SyntaxToken token) => token.Parent.IsKind(SyntaxKind.ThisConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) && constructorInit.ThisOrBaseKeyword == token; public bool IsBaseConstructorInitializer(SyntaxToken token) => token.Parent.IsKind(SyntaxKind.BaseConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) && constructorInit.ThisOrBaseKeyword == token; public bool IsQueryKeyword(SyntaxToken token) { switch (token.Kind()) { case SyntaxKind.FromKeyword: case SyntaxKind.JoinKeyword: case SyntaxKind.LetKeyword: case SyntaxKind.OrderByKeyword: case SyntaxKind.WhereKeyword: case SyntaxKind.OnKeyword: case SyntaxKind.EqualsKeyword: case SyntaxKind.InKeyword: return token.Parent is QueryClauseSyntax; case SyntaxKind.ByKeyword: case SyntaxKind.GroupKeyword: case SyntaxKind.SelectKeyword: return token.Parent is SelectOrGroupClauseSyntax; case SyntaxKind.AscendingKeyword: case SyntaxKind.DescendingKeyword: return token.Parent is OrderingSyntax; case SyntaxKind.IntoKeyword: return token.Parent.IsKind(SyntaxKind.JoinIntoClause, SyntaxKind.QueryContinuation); default: return false; } } public bool IsThrowExpression(SyntaxNode node) => node.Kind() == SyntaxKind.ThrowExpression; public bool IsPredefinedType(SyntaxToken token) => TryGetPredefinedType(token, out _); public bool IsPredefinedType(SyntaxToken token, PredefinedType type) => TryGetPredefinedType(token, out var actualType) && actualType == type; public bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type) { type = GetPredefinedType(token); return type != PredefinedType.None; } private static PredefinedType GetPredefinedType(SyntaxToken token) { return (SyntaxKind)token.RawKind switch { SyntaxKind.BoolKeyword => PredefinedType.Boolean, SyntaxKind.ByteKeyword => PredefinedType.Byte, SyntaxKind.SByteKeyword => PredefinedType.SByte, SyntaxKind.IntKeyword => PredefinedType.Int32, SyntaxKind.UIntKeyword => PredefinedType.UInt32, SyntaxKind.ShortKeyword => PredefinedType.Int16, SyntaxKind.UShortKeyword => PredefinedType.UInt16, SyntaxKind.LongKeyword => PredefinedType.Int64, SyntaxKind.ULongKeyword => PredefinedType.UInt64, SyntaxKind.FloatKeyword => PredefinedType.Single, SyntaxKind.DoubleKeyword => PredefinedType.Double, SyntaxKind.DecimalKeyword => PredefinedType.Decimal, SyntaxKind.StringKeyword => PredefinedType.String, SyntaxKind.CharKeyword => PredefinedType.Char, SyntaxKind.ObjectKeyword => PredefinedType.Object, SyntaxKind.VoidKeyword => PredefinedType.Void, _ => PredefinedType.None, }; } public bool IsPredefinedOperator(SyntaxToken token) => TryGetPredefinedOperator(token, out var actualOperator) && actualOperator != PredefinedOperator.None; public bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op) => TryGetPredefinedOperator(token, out var actualOperator) && actualOperator == op; public bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op) { op = GetPredefinedOperator(token); return op != PredefinedOperator.None; } private static PredefinedOperator GetPredefinedOperator(SyntaxToken token) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.PlusToken: case SyntaxKind.PlusEqualsToken: return PredefinedOperator.Addition; case SyntaxKind.MinusToken: case SyntaxKind.MinusEqualsToken: return PredefinedOperator.Subtraction; case SyntaxKind.AmpersandToken: case SyntaxKind.AmpersandEqualsToken: return PredefinedOperator.BitwiseAnd; case SyntaxKind.BarToken: case SyntaxKind.BarEqualsToken: return PredefinedOperator.BitwiseOr; case SyntaxKind.MinusMinusToken: return PredefinedOperator.Decrement; case SyntaxKind.PlusPlusToken: return PredefinedOperator.Increment; case SyntaxKind.SlashToken: case SyntaxKind.SlashEqualsToken: return PredefinedOperator.Division; case SyntaxKind.EqualsEqualsToken: return PredefinedOperator.Equality; case SyntaxKind.CaretToken: case SyntaxKind.CaretEqualsToken: return PredefinedOperator.ExclusiveOr; case SyntaxKind.GreaterThanToken: return PredefinedOperator.GreaterThan; case SyntaxKind.GreaterThanEqualsToken: return PredefinedOperator.GreaterThanOrEqual; case SyntaxKind.ExclamationEqualsToken: return PredefinedOperator.Inequality; case SyntaxKind.LessThanLessThanToken: case SyntaxKind.LessThanLessThanEqualsToken: return PredefinedOperator.LeftShift; case SyntaxKind.LessThanToken: return PredefinedOperator.LessThan; case SyntaxKind.LessThanEqualsToken: return PredefinedOperator.LessThanOrEqual; case SyntaxKind.AsteriskToken: case SyntaxKind.AsteriskEqualsToken: return PredefinedOperator.Multiplication; case SyntaxKind.PercentToken: case SyntaxKind.PercentEqualsToken: return PredefinedOperator.Modulus; case SyntaxKind.ExclamationToken: case SyntaxKind.TildeToken: return PredefinedOperator.Complement; case SyntaxKind.GreaterThanGreaterThanToken: case SyntaxKind.GreaterThanGreaterThanEqualsToken: return PredefinedOperator.RightShift; } return PredefinedOperator.None; } public string GetText(int kind) => SyntaxFacts.GetText((SyntaxKind)kind); public bool IsIdentifierStartCharacter(char c) => SyntaxFacts.IsIdentifierStartCharacter(c); public bool IsIdentifierPartCharacter(char c) => SyntaxFacts.IsIdentifierPartCharacter(c); public bool IsIdentifierEscapeCharacter(char c) => c == '@'; public bool IsValidIdentifier(string identifier) { var token = SyntaxFactory.ParseToken(identifier); return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length; } public bool IsVerbatimIdentifier(string identifier) { var token = SyntaxFactory.ParseToken(identifier); return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length && token.IsVerbatimIdentifier(); } public bool IsTypeCharacter(char c) => false; public bool IsStartOfUnicodeEscapeSequence(char c) => c == '\\'; public bool IsLiteral(SyntaxToken token) { switch (token.Kind()) { case SyntaxKind.NumericLiteralToken: case SyntaxKind.CharacterLiteralToken: case SyntaxKind.StringLiteralToken: case SyntaxKind.NullKeyword: case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.InterpolatedStringStartToken: case SyntaxKind.InterpolatedStringEndToken: case SyntaxKind.InterpolatedVerbatimStringStartToken: case SyntaxKind.InterpolatedStringTextToken: return true; default: return false; } } public bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token) => token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken); public bool IsNumericLiteralExpression([NotNullWhen(true)] SyntaxNode? node) => node?.IsKind(SyntaxKind.NumericLiteralExpression) == true; public bool IsTypeNamedVarInVariableOrFieldDeclaration(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent) { var typedToken = token; var typedParent = parent; if (typedParent.IsKind(SyntaxKind.IdentifierName)) { TypeSyntax? declaredType = null; if (typedParent.IsParentKind(SyntaxKind.VariableDeclaration, out VariableDeclarationSyntax? varDecl)) { declaredType = varDecl.Type; } else if (typedParent.IsParentKind(SyntaxKind.FieldDeclaration, out FieldDeclarationSyntax? fieldDecl)) { declaredType = fieldDecl.Declaration.Type; } return declaredType == typedParent && typedToken.ValueText == "var"; } return false; } public bool IsTypeNamedDynamic(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent) { if (parent is ExpressionSyntax typedParent) { if (SyntaxFacts.IsInTypeOnlyContext(typedParent) && typedParent.IsKind(SyntaxKind.IdentifierName) && token.ValueText == "dynamic") { return true; } } return false; } public bool IsBindableToken(SyntaxToken token) { if (this.IsWord(token) || this.IsLiteral(token) || this.IsOperator(token)) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.DelegateKeyword: case SyntaxKind.VoidKeyword: return false; } return true; } // In the order by clause a comma might be bound to ThenBy or ThenByDescending if (token.Kind() == SyntaxKind.CommaToken && token.Parent.IsKind(SyntaxKind.OrderByClause)) { return true; } return false; } public void GetPartsOfConditionalAccessExpression( SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull) { var conditionalAccess = (ConditionalAccessExpressionSyntax)node; expression = conditionalAccess.Expression; operatorToken = conditionalAccess.OperatorToken; whenNotNull = conditionalAccess.WhenNotNull; } public bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node) => node is PostfixUnaryExpressionSyntax; public bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node) => node is MemberBindingExpressionSyntax; public bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) => (node as MemberAccessExpressionSyntax)?.Kind() == SyntaxKind.PointerMemberAccessExpression; public void GetNameAndArityOfSimpleName(SyntaxNode? node, out string? name, out int arity) { name = null; arity = 0; if (node is SimpleNameSyntax simpleName) { name = simpleName.Identifier.ValueText; arity = simpleName.Arity; } } public bool LooksGeneric(SyntaxNode simpleName) => simpleName.IsKind(SyntaxKind.GenericName) || simpleName.GetLastToken().GetNextToken().Kind() == SyntaxKind.LessThanToken; public SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node) => (node as MemberBindingExpressionSyntax).GetParentConditionalAccessExpression()?.Expression; public SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node) => ((MemberBindingExpressionSyntax)node).Name; public SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode? node, bool allowImplicitTarget) => (node as MemberAccessExpressionSyntax)?.Expression; public void GetPartsOfElementAccessExpression(SyntaxNode? node, out SyntaxNode? expression, out SyntaxNode? argumentList) { var elementAccess = node as ElementAccessExpressionSyntax; expression = elementAccess?.Expression; argumentList = elementAccess?.ArgumentList; } public SyntaxNode? GetExpressionOfInterpolation(SyntaxNode? node) => (node as InterpolationSyntax)?.Expression; public bool IsInStaticContext(SyntaxNode node) => node.IsInStaticContext(); public bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node) => SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax); public bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.BaseList); public SyntaxNode? GetExpressionOfArgument(SyntaxNode? node) => (node as ArgumentSyntax)?.Expression; public RefKind GetRefKindOfArgument(SyntaxNode? node) => (node as ArgumentSyntax).GetRefKind(); public bool IsArgument([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.Argument); public bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node) { return node is ArgumentSyntax argument && argument.RefOrOutKeyword.Kind() == SyntaxKind.None && argument.NameColon == null; } public bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsInConstantContext(); public bool IsInConstructor(SyntaxNode node) => node.GetAncestor<ConstructorDeclarationSyntax>() != null; public bool IsUnsafeContext(SyntaxNode node) => node.IsUnsafeContext(); public SyntaxNode GetNameOfAttribute(SyntaxNode node) => ((AttributeSyntax)node).Name; public SyntaxNode GetExpressionOfParenthesizedExpression(SyntaxNode node) => ((ParenthesizedExpressionSyntax)node).Expression; public bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node) => (node as IdentifierNameSyntax).IsAttributeNamedArgumentIdentifier(); public SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position) { if (root == null) { throw new ArgumentNullException(nameof(root)); } if (position < 0 || position > root.Span.End) { throw new ArgumentOutOfRangeException(nameof(position)); } return root .FindToken(position) .GetAncestors<SyntaxNode>() .FirstOrDefault(n => n is BaseTypeDeclarationSyntax || n is DelegateDeclarationSyntax); } public SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node) => throw ExceptionUtilities.Unreachable; public SyntaxToken FindTokenOnLeftOfPosition( SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments) { return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments); } public SyntaxToken FindTokenOnRightOfPosition( SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments) { return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments); } public bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.IdentifierName) && node.IsParentKind(SyntaxKind.NameColon) && node.Parent.IsParentKind(SyntaxKind.Subpattern); public bool IsPropertyPatternClause(SyntaxNode node) => node.Kind() == SyntaxKind.PropertyPatternClause; public bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node) => IsMemberInitializerNamedAssignmentIdentifier(node, out _); public bool IsMemberInitializerNamedAssignmentIdentifier( [NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance) { initializedInstance = null; if (node is IdentifierNameSyntax identifier && identifier.IsLeftSideOfAssignExpression()) { if (identifier.Parent.IsParentKind(SyntaxKind.WithInitializerExpression)) { var withInitializer = identifier.Parent.GetRequiredParent(); initializedInstance = withInitializer.GetRequiredParent(); return true; } else if (identifier.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression)) { var objectInitializer = identifier.Parent.GetRequiredParent(); if (objectInitializer.Parent is BaseObjectCreationExpressionSyntax) { initializedInstance = objectInitializer.Parent; return true; } else if (objectInitializer.IsParentKind(SyntaxKind.SimpleAssignmentExpression, out AssignmentExpressionSyntax? assignment)) { initializedInstance = assignment.Left; return true; } } } return false; } public bool IsElementAccessExpression(SyntaxNode? node) => node.IsKind(SyntaxKind.ElementAccessExpression); [return: NotNullIfNotNull("node")] public SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false) => node.ConvertToSingleLine(useElasticTrivia); public void GetPartsOfParenthesizedExpression( SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen) { var parenthesizedExpression = (ParenthesizedExpressionSyntax)node; openParen = parenthesizedExpression.OpenParenToken; expression = parenthesizedExpression.Expression; closeParen = parenthesizedExpression.CloseParenToken; } public bool IsIndexerMemberCRef(SyntaxNode? node) => node.IsKind(SyntaxKind.IndexerMemberCref); public SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true) { Contract.ThrowIfNull(root, "root"); Contract.ThrowIfTrue(position < 0 || position > root.FullSpan.End, "position"); var end = root.FullSpan.End; if (end == 0) { // empty file return null; } // make sure position doesn't touch end of root position = Math.Min(position, end - 1); var node = root.FindToken(position).Parent; while (node != null) { if (useFullSpan || node.Span.Contains(position)) { var kind = node.Kind(); if ((kind != SyntaxKind.GlobalStatement) && (kind != SyntaxKind.IncompleteMember) && (node is MemberDeclarationSyntax)) { return node; } } node = node.Parent; } return null; } public bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node) { return node is BaseMethodDeclarationSyntax || node is BasePropertyDeclarationSyntax || node is EnumMemberDeclarationSyntax || node is BaseFieldDeclarationSyntax; } public bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node) { return node is BaseNamespaceDeclarationSyntax || node is TypeDeclarationSyntax || node is EnumDeclarationSyntax; } private const string dotToken = "."; public string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null) { if (node == null) { return string.Empty; } var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; // return type var memberDeclaration = node as MemberDeclarationSyntax; if ((options & DisplayNameOptions.IncludeType) != 0) { var type = memberDeclaration.GetMemberType(); if (type != null && !type.IsMissing) { builder.Append(type); builder.Append(' '); } } var names = ArrayBuilder<string?>.GetInstance(); // containing type(s) var parent = node.GetAncestor<TypeDeclarationSyntax>() ?? node.Parent; while (parent is TypeDeclarationSyntax) { names.Push(GetName(parent, options)); parent = parent.Parent; } // containing namespace(s) in source (if any) if ((options & DisplayNameOptions.IncludeNamespaces) != 0) { while (parent is BaseNamespaceDeclarationSyntax) { names.Add(GetName(parent, options)); parent = parent.Parent; } } while (!names.IsEmpty()) { var name = names.Pop(); if (name != null) { builder.Append(name); builder.Append(dotToken); } } // name (including generic type parameters) builder.Append(GetName(node, options)); // parameter list (if any) if ((options & DisplayNameOptions.IncludeParameters) != 0) { builder.Append(memberDeclaration.GetParameterList()); } return pooled.ToStringAndFree(); } private static string? GetName(SyntaxNode node, DisplayNameOptions options) { const string missingTokenPlaceholder = "?"; switch (node.Kind()) { case SyntaxKind.CompilationUnit: return null; case SyntaxKind.IdentifierName: var identifier = ((IdentifierNameSyntax)node).Identifier; return identifier.IsMissing ? missingTokenPlaceholder : identifier.Text; case SyntaxKind.IncompleteMember: return missingTokenPlaceholder; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return GetName(((BaseNamespaceDeclarationSyntax)node).Name, options); case SyntaxKind.QualifiedName: var qualified = (QualifiedNameSyntax)node; return GetName(qualified.Left, options) + dotToken + GetName(qualified.Right, options); } string? name = null; if (node is MemberDeclarationSyntax memberDeclaration) { if (memberDeclaration.Kind() == SyntaxKind.ConversionOperatorDeclaration) { name = (memberDeclaration as ConversionOperatorDeclarationSyntax)?.Type.ToString(); } else { var nameToken = memberDeclaration.GetNameToken(); if (nameToken != default) { name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text; if (memberDeclaration.Kind() == SyntaxKind.DestructorDeclaration) { name = "~" + name; } if ((options & DisplayNameOptions.IncludeTypeParameters) != 0) { var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; builder.Append(name); AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList()); name = pooled.ToStringAndFree(); } } else { Debug.Assert(memberDeclaration.Kind() == SyntaxKind.IncompleteMember); name = "?"; } } } else { if (node is VariableDeclaratorSyntax fieldDeclarator) { var nameToken = fieldDeclarator.Identifier; if (nameToken != default) { name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text; } } } Debug.Assert(name != null, "Unexpected node type " + node.Kind()); return name; } private static void AppendTypeParameterList(StringBuilder builder, TypeParameterListSyntax typeParameterList) { if (typeParameterList != null && typeParameterList.Parameters.Count > 0) { builder.Append('<'); builder.Append(typeParameterList.Parameters[0].Identifier.ValueText); for (var i = 1; i < typeParameterList.Parameters.Count; i++) { builder.Append(", "); builder.Append(typeParameterList.Parameters[i].Identifier.ValueText); } builder.Append('>'); } } public List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root) { var list = new List<SyntaxNode>(); AppendMembers(root, list, topLevel: true, methodLevel: true); return list; } public List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root) { var list = new List<SyntaxNode>(); AppendMembers(root, list, topLevel: false, methodLevel: true); return list; } public bool IsClassDeclaration([NotNullWhen(true)] SyntaxNode? node) => node?.Kind() == SyntaxKind.ClassDeclaration; public bool IsNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node) => node is BaseNamespaceDeclarationSyntax; public SyntaxNode? GetNameOfNamespaceDeclaration(SyntaxNode? node) => (node as BaseNamespaceDeclarationSyntax)?.Name; public SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration) => ((TypeDeclarationSyntax)typeDeclaration).Members; public SyntaxList<SyntaxNode> GetMembersOfNamespaceDeclaration(SyntaxNode namespaceDeclaration) => ((BaseNamespaceDeclarationSyntax)namespaceDeclaration).Members; public SyntaxList<SyntaxNode> GetMembersOfCompilationUnit(SyntaxNode compilationUnit) => ((CompilationUnitSyntax)compilationUnit).Members; public SyntaxList<SyntaxNode> GetImportsOfNamespaceDeclaration(SyntaxNode namespaceDeclaration) => ((BaseNamespaceDeclarationSyntax)namespaceDeclaration).Usings; public SyntaxList<SyntaxNode> GetImportsOfCompilationUnit(SyntaxNode compilationUnit) => ((CompilationUnitSyntax)compilationUnit).Usings; private void AppendMembers(SyntaxNode? node, List<SyntaxNode> list, bool topLevel, bool methodLevel) { Debug.Assert(topLevel || methodLevel); foreach (var member in node.GetMembers()) { if (IsTopLevelNodeWithMembers(member)) { if (topLevel) { list.Add(member); } AppendMembers(member, list, topLevel, methodLevel); continue; } if (methodLevel && IsMethodLevelMember(member)) { list.Add(member); } } } public TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node) { if (node.Span.IsEmpty) { return default; } var member = GetContainingMemberDeclaration(node, node.SpanStart); if (member == null) { return default; } // TODO: currently we only support method for now if (member is BaseMethodDeclarationSyntax method) { if (method.Body == null) { return default; } return GetBlockBodySpan(method.Body); } return default; } public bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span) { switch (node) { case ConstructorDeclarationSyntax constructor: return (constructor.Body != null && GetBlockBodySpan(constructor.Body).Contains(span)) || (constructor.Initializer != null && constructor.Initializer.Span.Contains(span)); case BaseMethodDeclarationSyntax method: return method.Body != null && GetBlockBodySpan(method.Body).Contains(span); case BasePropertyDeclarationSyntax property: return property.AccessorList != null && property.AccessorList.Span.Contains(span); case EnumMemberDeclarationSyntax @enum: return @enum.EqualsValue != null && @enum.EqualsValue.Span.Contains(span); case BaseFieldDeclarationSyntax field: return field.Declaration != null && field.Declaration.Span.Contains(span); } return false; } private static TextSpan GetBlockBodySpan(BlockSyntax body) => TextSpan.FromBounds(body.OpenBraceToken.Span.End, body.CloseBraceToken.SpanStart); public SyntaxNode? TryGetBindableParent(SyntaxToken token) { var node = token.Parent; while (node != null) { var parent = node.Parent; // If this node is on the left side of a member access expression, don't ascend // further or we'll end up binding to something else. if (parent is MemberAccessExpressionSyntax memberAccess) { if (memberAccess.Expression == node) { break; } } // If this node is on the left side of a qualified name, don't ascend // further or we'll end up binding to something else. if (parent is QualifiedNameSyntax qualifiedName) { if (qualifiedName.Left == node) { break; } } // If this node is on the left side of a alias-qualified name, don't ascend // further or we'll end up binding to something else. if (parent is AliasQualifiedNameSyntax aliasQualifiedName) { if (aliasQualifiedName.Alias == node) { break; } } // If this node is the type of an object creation expression, return the // object creation expression. if (parent is ObjectCreationExpressionSyntax objectCreation) { if (objectCreation.Type == node) { node = parent; break; } } // The inside of an interpolated string is treated as its own token so we // need to force navigation to the parent expression syntax. if (node is InterpolatedStringTextSyntax && parent is InterpolatedStringExpressionSyntax) { node = parent; break; } // If this node is not parented by a name, we're done. if (!(parent is NameSyntax)) { break; } node = parent; } if (node is VarPatternSyntax) { return node; } // Patterns are never bindable (though their constituent types/exprs may be). return node is PatternSyntax ? null : node; } public IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken) { if (!(root is CompilationUnitSyntax compilationUnit)) { return SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } var constructors = new List<SyntaxNode>(); AppendConstructors(compilationUnit.Members, constructors, cancellationToken); return constructors; } private void AppendConstructors(SyntaxList<MemberDeclarationSyntax> members, List<SyntaxNode> constructors, CancellationToken cancellationToken) { foreach (var member in members) { cancellationToken.ThrowIfCancellationRequested(); switch (member) { case ConstructorDeclarationSyntax constructor: constructors.Add(constructor); continue; case BaseNamespaceDeclarationSyntax @namespace: AppendConstructors(@namespace.Members, constructors, cancellationToken); break; case ClassDeclarationSyntax @class: AppendConstructors(@class.Members, constructors, cancellationToken); break; case RecordDeclarationSyntax record: AppendConstructors(record.Members, constructors, cancellationToken); break; case StructDeclarationSyntax @struct: AppendConstructors(@struct.Members, constructors, cancellationToken); break; } } } public bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace) { if (token.Kind() == SyntaxKind.CloseBraceToken) { var tuple = token.Parent.GetBraces(); openBrace = tuple.openBrace; return openBrace.Kind() == SyntaxKind.OpenBraceToken; } openBrace = default; return false; } public TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position, findInsideTrivia: false); if (trivia.Kind() == SyntaxKind.DisabledTextTrivia) { return trivia.FullSpan; } var token = syntaxTree.FindTokenOrEndToken(position, cancellationToken); if (token.Kind() == SyntaxKind.EndOfFileToken) { var triviaList = token.LeadingTrivia; foreach (var triviaTok in triviaList.Reverse()) { if (triviaTok.Span.Contains(position)) { return default; } if (triviaTok.Span.End < position) { if (!triviaTok.HasStructure) { return default; } var structure = triviaTok.GetStructure(); if (structure is BranchingDirectiveTriviaSyntax branch) { return !branch.IsActive || !branch.BranchTaken ? TextSpan.FromBounds(branch.FullSpan.Start, position) : default; } } } } return default; } public string GetNameForArgument(SyntaxNode? argument) => (argument as ArgumentSyntax)?.NameColon?.Name.Identifier.ValueText ?? string.Empty; public string GetNameForAttributeArgument(SyntaxNode? argument) => (argument as AttributeArgumentSyntax)?.NameEquals?.Name.Identifier.ValueText ?? string.Empty; public bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfDot(); public SyntaxNode? GetRightSideOfDot(SyntaxNode? node) { return (node as QualifiedNameSyntax)?.Right ?? (node as MemberAccessExpressionSyntax)?.Name; } public SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget) { return (node as QualifiedNameSyntax)?.Left ?? (node as MemberAccessExpressionSyntax)?.Expression; } public bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node) => (node as NameSyntax).IsLeftSideOfExplicitInterfaceSpecifier(); public bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfAssignExpression(); public bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfAnyAssignExpression(); public bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfCompoundAssignExpression(); public SyntaxNode? GetRightHandSideOfAssignment(SyntaxNode? node) => (node as AssignmentExpressionSyntax)?.Right; public bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.AnonymousObjectMemberDeclarator, out AnonymousObjectMemberDeclaratorSyntax? anonObject) && anonObject.NameEquals == null; public bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.PostIncrementExpression) || node.IsParentKind(SyntaxKind.PreIncrementExpression); public static bool IsOperandOfDecrementExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.PostDecrementExpression) || node.IsParentKind(SyntaxKind.PreDecrementExpression); public bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node) => IsOperandOfIncrementExpression(node) || IsOperandOfDecrementExpression(node); public SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString) => ((InterpolatedStringExpressionSyntax)interpolatedString).Contents; public bool IsVerbatimStringLiteral(SyntaxToken token) => token.IsVerbatimStringLiteral(); public bool IsNumericLiteral(SyntaxToken token) => token.Kind() == SyntaxKind.NumericLiteralToken; public void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList) { var invocation = (InvocationExpressionSyntax)node; expression = invocation.Expression; argumentList = invocation.ArgumentList; } public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode? invocationExpression) => GetArgumentsOfArgumentList((invocationExpression as InvocationExpressionSyntax)?.ArgumentList); public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode? objectCreationExpression) => GetArgumentsOfArgumentList((objectCreationExpression as BaseObjectCreationExpressionSyntax)?.ArgumentList); public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode? argumentList) => (argumentList as BaseArgumentListSyntax)?.Arguments ?? default; public SyntaxNode GetArgumentListOfInvocationExpression(SyntaxNode invocationExpression) => ((InvocationExpressionSyntax)invocationExpression).ArgumentList; public SyntaxNode? GetArgumentListOfObjectCreationExpression(SyntaxNode objectCreationExpression) => ((ObjectCreationExpressionSyntax)objectCreationExpression)!.ArgumentList; public bool IsRegularComment(SyntaxTrivia trivia) => trivia.IsRegularComment(); public bool IsDocumentationComment(SyntaxTrivia trivia) => trivia.IsDocComment(); public bool IsElastic(SyntaxTrivia trivia) => trivia.IsElastic(); public bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes) => trivia.IsPragmaDirective(out isDisable, out isActive, out errorCodes); public bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.DocumentationCommentExteriorTrivia; public bool IsDocumentationComment(SyntaxNode node) => SyntaxFacts.IsDocumentationCommentTrivia(node.Kind()); public bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node) { return node.IsKind(SyntaxKind.UsingDirective) || node.IsKind(SyntaxKind.ExternAliasDirective); } public bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node) => IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword); public bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node) => IsGlobalAttribute(node, SyntaxKind.ModuleKeyword); private static bool IsGlobalAttribute([NotNullWhen(true)] SyntaxNode? node, SyntaxKind attributeTarget) => node.IsKind(SyntaxKind.Attribute) && node.Parent.IsKind(SyntaxKind.AttributeList, out AttributeListSyntax? attributeList) && attributeList.Target?.Identifier.Kind() == attributeTarget; private static bool IsMemberDeclaration(SyntaxNode node) { // From the C# language spec: // class-member-declaration: // constant-declaration // field-declaration // method-declaration // property-declaration // event-declaration // indexer-declaration // operator-declaration // constructor-declaration // destructor-declaration // static-constructor-declaration // type-declaration switch (node.Kind()) { // Because fields declarations can define multiple symbols "public int a, b;" // We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name. case SyntaxKind.VariableDeclarator: return node.Parent.IsParentKind(SyntaxKind.FieldDeclaration) || node.Parent.IsParentKind(SyntaxKind.EventFieldDeclaration); case SyntaxKind.FieldDeclaration: case SyntaxKind.MethodDeclaration: case SyntaxKind.PropertyDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: return true; default: return false; } } public bool IsDeclaration(SyntaxNode node) => SyntaxFacts.IsNamespaceMemberDeclaration(node.Kind()) || IsMemberDeclaration(node); public bool IsTypeDeclaration(SyntaxNode node) => SyntaxFacts.IsTypeDeclaration(node.Kind()); public SyntaxNode? GetObjectCreationInitializer(SyntaxNode node) => ((ObjectCreationExpressionSyntax)node).Initializer; public SyntaxNode GetObjectCreationType(SyntaxNode node) => ((ObjectCreationExpressionSyntax)node).Type; public bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement) => statement.IsKind(SyntaxKind.ExpressionStatement, out ExpressionStatementSyntax? exprStatement) && exprStatement.Expression.IsKind(SyntaxKind.SimpleAssignmentExpression); public void GetPartsOfAssignmentStatement( SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { GetPartsOfAssignmentExpressionOrStatement( ((ExpressionStatementSyntax)statement).Expression, out left, out operatorToken, out right); } public void GetPartsOfAssignmentExpressionOrStatement( SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var expression = statement; if (statement is ExpressionStatementSyntax expressionStatement) { expression = expressionStatement.Expression; } var assignment = (AssignmentExpressionSyntax)expression; left = assignment.Left; operatorToken = assignment.OperatorToken; right = assignment.Right; } public SyntaxNode GetNameOfMemberAccessExpression(SyntaxNode memberAccessExpression) => ((MemberAccessExpressionSyntax)memberAccessExpression).Name; public void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name) { var memberAccess = (MemberAccessExpressionSyntax)node; expression = memberAccess.Expression; operatorToken = memberAccess.OperatorToken; name = memberAccess.Name; } public SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node) => ((SimpleNameSyntax)node).Identifier; public SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node) => ((VariableDeclaratorSyntax)node).Identifier; public SyntaxToken GetIdentifierOfParameter(SyntaxNode node) => ((ParameterSyntax)node).Identifier; public SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node) => ((IdentifierNameSyntax)node).Identifier; public bool IsLocalFunctionStatement([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.LocalFunctionStatement); public bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement) { return ((LocalDeclarationStatementSyntax)localDeclarationStatement).Declaration.Variables.Contains( (VariableDeclaratorSyntax)declarator); } public bool AreEquivalent(SyntaxToken token1, SyntaxToken token2) => SyntaxFactory.AreEquivalent(token1, token2); public bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2) => SyntaxFactory.AreEquivalent(node1, node2); public bool IsExpressionOfInvocationExpression([NotNullWhen(true)] SyntaxNode? node) => (node?.Parent as InvocationExpressionSyntax)?.Expression == node; public bool IsExpressionOfAwaitExpression([NotNullWhen(true)] SyntaxNode? node) => (node?.Parent as AwaitExpressionSyntax)?.Expression == node; public bool IsExpressionOfMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) => (node?.Parent as MemberAccessExpressionSyntax)?.Expression == node; public static SyntaxNode GetExpressionOfInvocationExpression(SyntaxNode node) => ((InvocationExpressionSyntax)node).Expression; public SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node) => ((AwaitExpressionSyntax)node).Expression; public bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node) => node?.Parent is ForEachStatementSyntax foreachStatement && foreachStatement.Expression == node; public SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node) => ((ExpressionStatementSyntax)node).Expression; public bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node) => node is BinaryExpressionSyntax; public bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.IsExpression); public void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var binaryExpression = (BinaryExpressionSyntax)node; left = binaryExpression.Left; operatorToken = binaryExpression.OperatorToken; right = binaryExpression.Right; } public void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse) { var conditionalExpression = (ConditionalExpressionSyntax)node; condition = conditionalExpression.Condition; whenTrue = conditionalExpression.WhenTrue; whenFalse = conditionalExpression.WhenFalse; } [return: NotNullIfNotNull("node")] public SyntaxNode? WalkDownParentheses(SyntaxNode? node) => (node as ExpressionSyntax)?.WalkDownParentheses() ?? node; public void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node, out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode { var tupleExpression = (TupleExpressionSyntax)node; openParen = tupleExpression.OpenParenToken; arguments = (SeparatedSyntaxList<TArgumentSyntax>)(SeparatedSyntaxList<SyntaxNode>)tupleExpression.Arguments; closeParen = tupleExpression.CloseParenToken; } public SyntaxNode GetOperandOfPrefixUnaryExpression(SyntaxNode node) => ((PrefixUnaryExpressionSyntax)node).Operand; public SyntaxToken GetOperatorTokenOfPrefixUnaryExpression(SyntaxNode node) => ((PrefixUnaryExpressionSyntax)node).OperatorToken; public SyntaxNode? GetNextExecutableStatement(SyntaxNode statement) => ((StatementSyntax)statement).GetNextStatement(); public override bool IsSingleLineCommentTrivia(SyntaxTrivia trivia) => trivia.IsSingleLineComment(); public override bool IsMultiLineCommentTrivia(SyntaxTrivia trivia) => trivia.IsMultiLineComment(); public override bool IsSingleLineDocCommentTrivia(SyntaxTrivia trivia) => trivia.IsSingleLineDocComment(); public override bool IsMultiLineDocCommentTrivia(SyntaxTrivia trivia) => trivia.IsMultiLineDocComment(); public override bool IsShebangDirectiveTrivia(SyntaxTrivia trivia) => trivia.IsShebangDirective(); public override bool IsPreprocessorDirective(SyntaxTrivia trivia) => SyntaxFacts.IsPreprocessorDirective(trivia.Kind()); public bool IsOnTypeHeader(SyntaxNode root, int position, bool fullHeader, [NotNullWhen(true)] out SyntaxNode? typeDeclaration) { var node = TryGetAncestorForLocation<BaseTypeDeclarationSyntax>(root, position); typeDeclaration = node; if (node == null) return false; var lastToken = (node as TypeDeclarationSyntax)?.TypeParameterList?.GetLastToken() ?? node.Identifier; if (fullHeader) lastToken = node.BaseList?.GetLastToken() ?? lastToken; return IsOnHeader(root, position, node, lastToken); } public bool IsOnPropertyDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? propertyDeclaration) { var node = TryGetAncestorForLocation<PropertyDeclarationSyntax>(root, position); propertyDeclaration = node; if (propertyDeclaration == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.Identifier); } public bool IsOnParameterHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? parameter) { var node = TryGetAncestorForLocation<ParameterSyntax>(root, position); parameter = node; if (parameter == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node); } public bool IsOnMethodHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? method) { var node = TryGetAncestorForLocation<MethodDeclarationSyntax>(root, position); method = node; if (method == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.ParameterList); } public bool IsOnLocalFunctionHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localFunction) { var node = TryGetAncestorForLocation<LocalFunctionStatementSyntax>(root, position); localFunction = node; if (localFunction == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.ParameterList); } public bool IsOnLocalDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localDeclaration) { var node = TryGetAncestorForLocation<LocalDeclarationStatementSyntax>(root, position); localDeclaration = node; if (localDeclaration == null) { return false; } var initializersExpressions = node!.Declaration.Variables .Where(v => v.Initializer != null) .SelectAsArray(initializedV => initializedV.Initializer!.Value); return IsOnHeader(root, position, node, node, holes: initializersExpressions); } public bool IsOnIfStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? ifStatement) { var node = TryGetAncestorForLocation<IfStatementSyntax>(root, position); ifStatement = node; if (ifStatement == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.CloseParenToken); } public bool IsOnWhileStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? whileStatement) { var node = TryGetAncestorForLocation<WhileStatementSyntax>(root, position); whileStatement = node; if (whileStatement == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.CloseParenToken); } public bool IsOnForeachHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? foreachStatement) { var node = TryGetAncestorForLocation<ForEachStatementSyntax>(root, position); foreachStatement = node; if (foreachStatement == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.CloseParenToken); } public bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration) { var token = root.FindToken(position); var typeDecl = token.GetAncestor<TypeDeclarationSyntax>(); typeDeclaration = typeDecl; if (typeDecl == null) { return false; } RoslynDebug.AssertNotNull(typeDeclaration); if (position < typeDecl.OpenBraceToken.Span.End || position > typeDecl.CloseBraceToken.Span.Start) { return false; } var line = sourceText.Lines.GetLineFromPosition(position); if (!line.IsEmptyOrWhitespace()) { return false; } var member = typeDecl.Members.FirstOrDefault(d => d.FullSpan.Contains(position)); if (member == null) { // 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) { foreach (var trivia in member.GetLeadingTrivia()) { if (!trivia.IsWhitespaceOrEndOfLine()) { return false; } if (trivia.FullSpan.Contains(position)) { return true; } } } } return false; } protected override bool ContainsInterleavedDirective(TextSpan span, SyntaxToken token, CancellationToken cancellationToken) => token.ContainsInterleavedDirective(span, cancellationToken); public SyntaxTokenList GetModifiers(SyntaxNode? node) => node.GetModifiers(); public SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers) => node.WithModifiers(modifiers); public bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node) => node is LiteralExpressionSyntax; public SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node) => ((LocalDeclarationStatementSyntax)node).Declaration.Variables; public SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node) => ((VariableDeclaratorSyntax)node).Initializer; public SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node) => ((VariableDeclarationSyntax)((VariableDeclaratorSyntax)node).Parent!).Type; public SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node) => ((EqualsValueClauseSyntax?)node)?.Value; public bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.Block); public bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.Block, SyntaxKind.SwitchSection, SyntaxKind.CompilationUnit); public IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node) { return node switch { BlockSyntax block => block.Statements, SwitchSectionSyntax switchSection => switchSection.Statements, CompilationUnitSyntax compilationUnit => compilationUnit.Members.OfType<GlobalStatementSyntax>().SelectAsArray(globalStatement => globalStatement.Statement), _ => throw ExceptionUtilities.UnexpectedValue(node), }; } public SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes) => nodes.FindInnermostCommonNode(node => IsExecutableBlock(node)); public bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node) => IsExecutableBlock(node) || node.IsEmbeddedStatementOwner(); public IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node) { if (IsExecutableBlock(node)) return GetExecutableBlockStatements(node); else if (node.GetEmbeddedStatement() is { } embeddedStatement) return ImmutableArray.Create<SyntaxNode>(embeddedStatement); else return ImmutableArray<SyntaxNode>.Empty; } public bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node) => node is CastExpressionSyntax; public bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node) => node is CastExpressionSyntax; public void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression) { var cast = (CastExpressionSyntax)node; type = cast.Type; expression = cast.Expression; } public SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token) { if (token.Kind() == SyntaxKind.OverrideKeyword && token.Parent is MemberDeclarationSyntax member) { return member.GetNameToken(); } return null; } public override SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node) => node.GetAttributeLists(); public override bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.XmlElement, out XmlElementSyntax? xmlElement) && xmlElement.StartTag.Name.LocalName.ValueText == DocumentationCommentXmlNames.ParameterElementName; public override SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia) { if (trivia.GetStructure() is DocumentationCommentTriviaSyntax documentationCommentTrivia) { return documentationCommentTrivia.Content; } throw ExceptionUtilities.UnexpectedValue(trivia.Kind()); } public override bool CanHaveAccessibility(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.DelegateDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return true; case SyntaxKind.VariableDeclaration: case SyntaxKind.VariableDeclarator: var declarationKind = this.GetDeclarationKind(declaration); return declarationKind == DeclarationKind.Field || declarationKind == DeclarationKind.Event; case SyntaxKind.ConstructorDeclaration: // Static constructor can't have accessibility return !((ConstructorDeclarationSyntax)declaration).Modifiers.Any(SyntaxKind.StaticKeyword); case SyntaxKind.PropertyDeclaration: return ((PropertyDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null; case SyntaxKind.IndexerDeclaration: return ((IndexerDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)declaration; if (method.ExplicitInterfaceSpecifier != null) { // explicit interface methods can't have accessibility. return false; } if (method.Modifiers.Any(SyntaxKind.PartialKeyword)) { // partial methods can't have accessibility modifiers. return false; } return true; case SyntaxKind.EventDeclaration: return ((EventDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null; default: return false; } } public override Accessibility GetAccessibility(SyntaxNode declaration) { if (!CanHaveAccessibility(declaration)) { return Accessibility.NotApplicable; } var modifierTokens = GetModifierTokens(declaration); GetAccessibilityAndModifiers(modifierTokens, out var accessibility, out _, out _); return accessibility; } public override void GetAccessibilityAndModifiers(SyntaxTokenList modifierList, out Accessibility accessibility, out DeclarationModifiers modifiers, out bool isDefault) { accessibility = Accessibility.NotApplicable; modifiers = DeclarationModifiers.None; isDefault = false; foreach (var token in modifierList) { accessibility = (token.Kind(), accessibility) switch { (SyntaxKind.PublicKeyword, _) => Accessibility.Public, (SyntaxKind.PrivateKeyword, Accessibility.Protected) => Accessibility.ProtectedAndInternal, (SyntaxKind.PrivateKeyword, _) => Accessibility.Private, (SyntaxKind.InternalKeyword, Accessibility.Protected) => Accessibility.ProtectedOrInternal, (SyntaxKind.InternalKeyword, _) => Accessibility.Internal, (SyntaxKind.ProtectedKeyword, Accessibility.Private) => Accessibility.ProtectedAndInternal, (SyntaxKind.ProtectedKeyword, Accessibility.Internal) => Accessibility.ProtectedOrInternal, (SyntaxKind.ProtectedKeyword, _) => Accessibility.Protected, _ => accessibility, }; modifiers |= token.Kind() switch { SyntaxKind.AbstractKeyword => DeclarationModifiers.Abstract, SyntaxKind.NewKeyword => DeclarationModifiers.New, SyntaxKind.OverrideKeyword => DeclarationModifiers.Override, SyntaxKind.VirtualKeyword => DeclarationModifiers.Virtual, SyntaxKind.StaticKeyword => DeclarationModifiers.Static, SyntaxKind.AsyncKeyword => DeclarationModifiers.Async, SyntaxKind.ConstKeyword => DeclarationModifiers.Const, SyntaxKind.ReadOnlyKeyword => DeclarationModifiers.ReadOnly, SyntaxKind.SealedKeyword => DeclarationModifiers.Sealed, SyntaxKind.UnsafeKeyword => DeclarationModifiers.Unsafe, SyntaxKind.PartialKeyword => DeclarationModifiers.Partial, SyntaxKind.RefKeyword => DeclarationModifiers.Ref, SyntaxKind.VolatileKeyword => DeclarationModifiers.Volatile, SyntaxKind.ExternKeyword => DeclarationModifiers.Extern, _ => DeclarationModifiers.None, }; isDefault |= token.Kind() == SyntaxKind.DefaultKeyword; } } public override SyntaxTokenList GetModifierTokens(SyntaxNode? declaration) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.Modifiers, ParameterSyntax parameter => parameter.Modifiers, LocalDeclarationStatementSyntax localDecl => localDecl.Modifiers, LocalFunctionStatementSyntax localFunc => localFunc.Modifiers, AccessorDeclarationSyntax accessor => accessor.Modifiers, VariableDeclarationSyntax varDecl => GetModifierTokens(varDecl.Parent), VariableDeclaratorSyntax varDecl => GetModifierTokens(varDecl.Parent), AnonymousFunctionExpressionSyntax anonymous => anonymous.Modifiers, _ => default, }; public override DeclarationKind GetDeclarationKind(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: return DeclarationKind.Class; case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: return DeclarationKind.Struct; case SyntaxKind.InterfaceDeclaration: return DeclarationKind.Interface; case SyntaxKind.EnumDeclaration: return DeclarationKind.Enum; case SyntaxKind.DelegateDeclaration: return DeclarationKind.Delegate; case SyntaxKind.MethodDeclaration: return DeclarationKind.Method; case SyntaxKind.OperatorDeclaration: return DeclarationKind.Operator; case SyntaxKind.ConversionOperatorDeclaration: return DeclarationKind.ConversionOperator; case SyntaxKind.ConstructorDeclaration: return DeclarationKind.Constructor; case SyntaxKind.DestructorDeclaration: return DeclarationKind.Destructor; case SyntaxKind.PropertyDeclaration: return DeclarationKind.Property; case SyntaxKind.IndexerDeclaration: return DeclarationKind.Indexer; case SyntaxKind.EventDeclaration: return DeclarationKind.CustomEvent; case SyntaxKind.EnumMemberDeclaration: return DeclarationKind.EnumMember; case SyntaxKind.CompilationUnit: return DeclarationKind.CompilationUnit; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return DeclarationKind.Namespace; case SyntaxKind.UsingDirective: return DeclarationKind.NamespaceImport; case SyntaxKind.Parameter: return DeclarationKind.Parameter; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: return DeclarationKind.LambdaExpression; case SyntaxKind.FieldDeclaration: var fd = (FieldDeclarationSyntax)declaration; if (fd.Declaration != null && fd.Declaration.Variables.Count == 1) { // this node is considered the declaration if it contains only one variable. return DeclarationKind.Field; } else { return DeclarationKind.None; } case SyntaxKind.EventFieldDeclaration: var ef = (EventFieldDeclarationSyntax)declaration; if (ef.Declaration != null && ef.Declaration.Variables.Count == 1) { // this node is considered the declaration if it contains only one variable. return DeclarationKind.Event; } else { return DeclarationKind.None; } case SyntaxKind.LocalDeclarationStatement: var ld = (LocalDeclarationStatementSyntax)declaration; if (ld.Declaration != null && ld.Declaration.Variables.Count == 1) { // this node is considered the declaration if it contains only one variable. return DeclarationKind.Variable; } else { return DeclarationKind.None; } case SyntaxKind.VariableDeclaration: { var vd = (VariableDeclarationSyntax)declaration; if (vd.Variables.Count == 1 && vd.Parent == null) { // this node is the declaration if it contains only one variable and has no parent. return DeclarationKind.Variable; } else { return DeclarationKind.None; } } case SyntaxKind.VariableDeclarator: { var vd = declaration.Parent as VariableDeclarationSyntax; // this node is considered the declaration if it is one among many, or it has no parent if (vd == null || vd.Variables.Count > 1) { if (ParentIsFieldDeclaration(vd)) { return DeclarationKind.Field; } else if (ParentIsEventFieldDeclaration(vd)) { return DeclarationKind.Event; } else { return DeclarationKind.Variable; } } break; } case SyntaxKind.AttributeList: var list = (AttributeListSyntax)declaration; if (list.Attributes.Count == 1) { return DeclarationKind.Attribute; } break; case SyntaxKind.Attribute: if (!(declaration.Parent is AttributeListSyntax parentList) || parentList.Attributes.Count > 1) { return DeclarationKind.Attribute; } break; case SyntaxKind.GetAccessorDeclaration: return DeclarationKind.GetAccessor; case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: return DeclarationKind.SetAccessor; case SyntaxKind.AddAccessorDeclaration: return DeclarationKind.AddAccessor; case SyntaxKind.RemoveAccessorDeclaration: return DeclarationKind.RemoveAccessor; } return DeclarationKind.None; } internal static bool ParentIsFieldDeclaration([NotNullWhen(true)] SyntaxNode? node) => node?.Parent.IsKind(SyntaxKind.FieldDeclaration) ?? false; internal static bool ParentIsEventFieldDeclaration([NotNullWhen(true)] SyntaxNode? node) => node?.Parent.IsKind(SyntaxKind.EventFieldDeclaration) ?? false; internal static bool ParentIsLocalDeclarationStatement([NotNullWhen(true)] SyntaxNode? node) => node?.Parent.IsKind(SyntaxKind.LocalDeclarationStatement) ?? false; public bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.IsPatternExpression); public void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right) { var isPatternExpression = (IsPatternExpressionSyntax)node; left = isPatternExpression.Expression; isToken = isPatternExpression.IsKeyword; right = isPatternExpression.Pattern; } public bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node) => node is PatternSyntax; public bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ConstantPattern); public bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.DeclarationPattern); public bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.RecursivePattern); public bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.VarPattern); public SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node) => ((ConstantPatternSyntax)node).Expression; public void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation) { var declarationPattern = (DeclarationPatternSyntax)node; type = declarationPattern.Type; designation = declarationPattern.Designation; } public void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation) { var recursivePattern = (RecursivePatternSyntax)node; type = recursivePattern.Type; positionalPart = recursivePattern.PositionalPatternClause; propertyPart = recursivePattern.PropertyPatternClause; designation = recursivePattern.Designation; } public bool SupportsNotPattern(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion.IsCSharp9OrAbove(); public bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.AndPattern); public bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node) => node is BinaryPatternSyntax; public bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.NotPattern); public bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.OrPattern); public bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ParenthesizedPattern); public bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.TypePattern); public bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node) => node is UnaryPatternSyntax; public void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen) { var parenthesizedPattern = (ParenthesizedPatternSyntax)node; openParen = parenthesizedPattern.OpenParenToken; pattern = parenthesizedPattern.Pattern; closeParen = parenthesizedPattern.CloseParenToken; } public void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var binaryPattern = (BinaryPatternSyntax)node; left = binaryPattern.Left; operatorToken = binaryPattern.OperatorToken; right = binaryPattern.Right; } public void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern) { var unaryPattern = (UnaryPatternSyntax)node; operatorToken = unaryPattern.OperatorToken; pattern = unaryPattern.Pattern; } public SyntaxNode GetTypeOfTypePattern(SyntaxNode node) => ((TypePatternSyntax)node).Type; public bool IsImplicitObjectCreation([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ImplicitObjectCreationExpression); public SyntaxNode GetExpressionOfThrowExpression(SyntaxNode throwExpression) => ((ThrowExpressionSyntax)throwExpression).Expression; public bool IsThrowStatement([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ThrowStatement); public bool IsLocalFunction([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.LocalFunctionStatement); public void GetPartsOfInterpolationExpression(SyntaxNode node, out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken) { var interpolatedStringExpression = (InterpolatedStringExpressionSyntax)node; stringStartToken = interpolatedStringExpression.StringStartToken; contents = interpolatedStringExpression.Contents; stringEndToken = interpolatedStringExpression.StringEndToken; } public bool IsVerbatimInterpolatedStringExpression(SyntaxNode node) => node is InterpolatedStringExpressionSyntax interpolatedString && interpolatedString.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Shared.Extensions; #if CODE_STYLE using Microsoft.CodeAnalysis.Internal.Editing; #else using Microsoft.CodeAnalysis.Editing; #endif namespace Microsoft.CodeAnalysis.CSharp.LanguageServices { internal class CSharpSyntaxFacts : AbstractSyntaxFacts, ISyntaxFacts { internal static readonly CSharpSyntaxFacts Instance = new(); protected CSharpSyntaxFacts() { } public bool IsCaseSensitive => true; public StringComparer StringComparer { get; } = StringComparer.Ordinal; public SyntaxTrivia ElasticMarker => SyntaxFactory.ElasticMarker; public SyntaxTrivia ElasticCarriageReturnLineFeed => SyntaxFactory.ElasticCarriageReturnLineFeed; public override ISyntaxKinds SyntaxKinds { get; } = CSharpSyntaxKinds.Instance; protected override IDocumentationCommentService DocumentationCommentService => CSharpDocumentationCommentService.Instance; public bool SupportsIndexingInitializer(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp6; public bool SupportsThrowExpression(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7; public bool SupportsLocalFunctionDeclaration(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7; public bool SupportsRecord(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp9; public bool SupportsRecordStruct(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion.IsCSharp10OrAbove(); public SyntaxToken ParseToken(string text) => SyntaxFactory.ParseToken(text); public SyntaxTriviaList ParseLeadingTrivia(string text) => SyntaxFactory.ParseLeadingTrivia(text); public string EscapeIdentifier(string identifier) { var nullIndex = identifier.IndexOf('\0'); if (nullIndex >= 0) { identifier = identifier.Substring(0, nullIndex); } var needsEscaping = SyntaxFacts.GetKeywordKind(identifier) != SyntaxKind.None; return needsEscaping ? "@" + identifier : identifier; } public bool IsVerbatimIdentifier(SyntaxToken token) => token.IsVerbatimIdentifier(); public bool IsOperator(SyntaxToken token) { var kind = token.Kind(); return (SyntaxFacts.IsAnyUnaryExpression(kind) && (token.Parent is PrefixUnaryExpressionSyntax || token.Parent is PostfixUnaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) || (SyntaxFacts.IsBinaryExpression(kind) && (token.Parent is BinaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) || (SyntaxFacts.IsAssignmentExpressionOperatorToken(kind) && token.Parent is AssignmentExpressionSyntax); } public bool IsReservedKeyword(SyntaxToken token) => SyntaxFacts.IsReservedKeyword(token.Kind()); public bool IsContextualKeyword(SyntaxToken token) => SyntaxFacts.IsContextualKeyword(token.Kind()); public bool IsPreprocessorKeyword(SyntaxToken token) => SyntaxFacts.IsPreprocessorKeyword(token.Kind()); public bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) => syntaxTree.IsPreProcessorDirectiveContext( position, syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true), cancellationToken); public bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken) { if (syntaxTree == null) { return false; } return syntaxTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken); } public bool IsDirective([NotNullWhen(true)] SyntaxNode? node) => node is DirectiveTriviaSyntax; public bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? node, out ExternalSourceInfo info) { if (node is LineDirectiveTriviaSyntax lineDirective) { if (lineDirective.Line.Kind() == SyntaxKind.DefaultKeyword) { info = new ExternalSourceInfo(null, ends: true); return true; } else if (lineDirective.Line.Kind() == SyntaxKind.NumericLiteralToken && lineDirective.Line.Value is int) { info = new ExternalSourceInfo((int)lineDirective.Line.Value, false); return true; } } info = default; return false; } public bool IsRightSideOfQualifiedName([NotNullWhen(true)] SyntaxNode? node) { var name = node as SimpleNameSyntax; return name.IsRightSideOfQualifiedName(); } public bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) { var name = node as SimpleNameSyntax; return name.IsSimpleMemberAccessExpressionName(); } public bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) => node?.Parent is MemberAccessExpressionSyntax memberAccess && memberAccess.Name == node; public bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node) { var name = node as SimpleNameSyntax; return name.IsMemberBindingExpressionName(); } [return: NotNullIfNotNull("node")] public SyntaxNode? GetStandaloneExpression(SyntaxNode? node) => node is ExpressionSyntax expression ? SyntaxFactory.GetStandaloneExpression(expression) : node; public SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node) => node.GetRootConditionalAccessExpression(); public bool IsObjectCreationExpressionType([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.ObjectCreationExpression, out ObjectCreationExpressionSyntax? objectCreation) && objectCreation.Type == node; public bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node) => node is DeclarationExpressionSyntax; public bool IsAttributeName(SyntaxNode node) => SyntaxFacts.IsAttributeName(node); public bool IsAnonymousFunction([NotNullWhen(true)] SyntaxNode? node) { return node is ParenthesizedLambdaExpressionSyntax || node is SimpleLambdaExpressionSyntax || node is AnonymousMethodExpressionSyntax; } public bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node) => node is ArgumentSyntax arg && arg.NameColon != null; public bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node) => node.CheckParent<NameColonSyntax>(p => p.Name == node); public SyntaxToken? GetNameOfParameter(SyntaxNode? node) => (node as ParameterSyntax)?.Identifier; public SyntaxNode? GetDefaultOfParameter(SyntaxNode? node) => (node as ParameterSyntax)?.Default; public SyntaxNode? GetParameterList(SyntaxNode node) => node.GetParameterList(); public bool IsParameterList([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ParameterList, SyntaxKind.BracketedParameterList); public SyntaxToken GetIdentifierOfGenericName(SyntaxNode? genericName) { return genericName is GenericNameSyntax csharpGenericName ? csharpGenericName.Identifier : default; } public bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.UsingDirective, out UsingDirectiveSyntax? usingDirective) && usingDirective.Name == node; public bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node) => node is UsingDirectiveSyntax usingDirectiveNode && usingDirectiveNode.Alias != null; public bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node) => node is ForEachVariableStatementSyntax; public bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node) => node is AssignmentExpressionSyntax assignment && assignment.IsDeconstruction(); public Location GetDeconstructionReferenceLocation(SyntaxNode node) { return node switch { AssignmentExpressionSyntax assignment => assignment.Left.GetLocation(), ForEachVariableStatementSyntax @foreach => @foreach.Variable.GetLocation(), _ => throw ExceptionUtilities.UnexpectedValue(node.Kind()), }; } public bool IsStatement([NotNullWhen(true)] SyntaxNode? node) => node is StatementSyntax; public bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node) => node is StatementSyntax; public bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node) { if (node is BlockSyntax || node is ArrowExpressionClauseSyntax) { return node.Parent is BaseMethodDeclarationSyntax || node.Parent is AccessorDeclarationSyntax; } return false; } public SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode? node) => (node as ReturnStatementSyntax)?.Expression; public bool IsThisConstructorInitializer(SyntaxToken token) => token.Parent.IsKind(SyntaxKind.ThisConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) && constructorInit.ThisOrBaseKeyword == token; public bool IsBaseConstructorInitializer(SyntaxToken token) => token.Parent.IsKind(SyntaxKind.BaseConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) && constructorInit.ThisOrBaseKeyword == token; public bool IsQueryKeyword(SyntaxToken token) { switch (token.Kind()) { case SyntaxKind.FromKeyword: case SyntaxKind.JoinKeyword: case SyntaxKind.LetKeyword: case SyntaxKind.OrderByKeyword: case SyntaxKind.WhereKeyword: case SyntaxKind.OnKeyword: case SyntaxKind.EqualsKeyword: case SyntaxKind.InKeyword: return token.Parent is QueryClauseSyntax; case SyntaxKind.ByKeyword: case SyntaxKind.GroupKeyword: case SyntaxKind.SelectKeyword: return token.Parent is SelectOrGroupClauseSyntax; case SyntaxKind.AscendingKeyword: case SyntaxKind.DescendingKeyword: return token.Parent is OrderingSyntax; case SyntaxKind.IntoKeyword: return token.Parent.IsKind(SyntaxKind.JoinIntoClause, SyntaxKind.QueryContinuation); default: return false; } } public bool IsThrowExpression(SyntaxNode node) => node.Kind() == SyntaxKind.ThrowExpression; public bool IsPredefinedType(SyntaxToken token) => TryGetPredefinedType(token, out _); public bool IsPredefinedType(SyntaxToken token, PredefinedType type) => TryGetPredefinedType(token, out var actualType) && actualType == type; public bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type) { type = GetPredefinedType(token); return type != PredefinedType.None; } private static PredefinedType GetPredefinedType(SyntaxToken token) { return (SyntaxKind)token.RawKind switch { SyntaxKind.BoolKeyword => PredefinedType.Boolean, SyntaxKind.ByteKeyword => PredefinedType.Byte, SyntaxKind.SByteKeyword => PredefinedType.SByte, SyntaxKind.IntKeyword => PredefinedType.Int32, SyntaxKind.UIntKeyword => PredefinedType.UInt32, SyntaxKind.ShortKeyword => PredefinedType.Int16, SyntaxKind.UShortKeyword => PredefinedType.UInt16, SyntaxKind.LongKeyword => PredefinedType.Int64, SyntaxKind.ULongKeyword => PredefinedType.UInt64, SyntaxKind.FloatKeyword => PredefinedType.Single, SyntaxKind.DoubleKeyword => PredefinedType.Double, SyntaxKind.DecimalKeyword => PredefinedType.Decimal, SyntaxKind.StringKeyword => PredefinedType.String, SyntaxKind.CharKeyword => PredefinedType.Char, SyntaxKind.ObjectKeyword => PredefinedType.Object, SyntaxKind.VoidKeyword => PredefinedType.Void, _ => PredefinedType.None, }; } public bool IsPredefinedOperator(SyntaxToken token) => TryGetPredefinedOperator(token, out var actualOperator) && actualOperator != PredefinedOperator.None; public bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op) => TryGetPredefinedOperator(token, out var actualOperator) && actualOperator == op; public bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op) { op = GetPredefinedOperator(token); return op != PredefinedOperator.None; } private static PredefinedOperator GetPredefinedOperator(SyntaxToken token) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.PlusToken: case SyntaxKind.PlusEqualsToken: return PredefinedOperator.Addition; case SyntaxKind.MinusToken: case SyntaxKind.MinusEqualsToken: return PredefinedOperator.Subtraction; case SyntaxKind.AmpersandToken: case SyntaxKind.AmpersandEqualsToken: return PredefinedOperator.BitwiseAnd; case SyntaxKind.BarToken: case SyntaxKind.BarEqualsToken: return PredefinedOperator.BitwiseOr; case SyntaxKind.MinusMinusToken: return PredefinedOperator.Decrement; case SyntaxKind.PlusPlusToken: return PredefinedOperator.Increment; case SyntaxKind.SlashToken: case SyntaxKind.SlashEqualsToken: return PredefinedOperator.Division; case SyntaxKind.EqualsEqualsToken: return PredefinedOperator.Equality; case SyntaxKind.CaretToken: case SyntaxKind.CaretEqualsToken: return PredefinedOperator.ExclusiveOr; case SyntaxKind.GreaterThanToken: return PredefinedOperator.GreaterThan; case SyntaxKind.GreaterThanEqualsToken: return PredefinedOperator.GreaterThanOrEqual; case SyntaxKind.ExclamationEqualsToken: return PredefinedOperator.Inequality; case SyntaxKind.LessThanLessThanToken: case SyntaxKind.LessThanLessThanEqualsToken: return PredefinedOperator.LeftShift; case SyntaxKind.LessThanToken: return PredefinedOperator.LessThan; case SyntaxKind.LessThanEqualsToken: return PredefinedOperator.LessThanOrEqual; case SyntaxKind.AsteriskToken: case SyntaxKind.AsteriskEqualsToken: return PredefinedOperator.Multiplication; case SyntaxKind.PercentToken: case SyntaxKind.PercentEqualsToken: return PredefinedOperator.Modulus; case SyntaxKind.ExclamationToken: case SyntaxKind.TildeToken: return PredefinedOperator.Complement; case SyntaxKind.GreaterThanGreaterThanToken: case SyntaxKind.GreaterThanGreaterThanEqualsToken: return PredefinedOperator.RightShift; } return PredefinedOperator.None; } public string GetText(int kind) => SyntaxFacts.GetText((SyntaxKind)kind); public bool IsIdentifierStartCharacter(char c) => SyntaxFacts.IsIdentifierStartCharacter(c); public bool IsIdentifierPartCharacter(char c) => SyntaxFacts.IsIdentifierPartCharacter(c); public bool IsIdentifierEscapeCharacter(char c) => c == '@'; public bool IsValidIdentifier(string identifier) { var token = SyntaxFactory.ParseToken(identifier); return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length; } public bool IsVerbatimIdentifier(string identifier) { var token = SyntaxFactory.ParseToken(identifier); return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length && token.IsVerbatimIdentifier(); } public bool IsTypeCharacter(char c) => false; public bool IsStartOfUnicodeEscapeSequence(char c) => c == '\\'; public bool IsLiteral(SyntaxToken token) { switch (token.Kind()) { case SyntaxKind.NumericLiteralToken: case SyntaxKind.CharacterLiteralToken: case SyntaxKind.StringLiteralToken: case SyntaxKind.NullKeyword: case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.InterpolatedStringStartToken: case SyntaxKind.InterpolatedStringEndToken: case SyntaxKind.InterpolatedVerbatimStringStartToken: case SyntaxKind.InterpolatedStringTextToken: return true; default: return false; } } public bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token) => token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken); public bool IsNumericLiteralExpression([NotNullWhen(true)] SyntaxNode? node) => node?.IsKind(SyntaxKind.NumericLiteralExpression) == true; public bool IsTypeNamedVarInVariableOrFieldDeclaration(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent) { var typedToken = token; var typedParent = parent; if (typedParent.IsKind(SyntaxKind.IdentifierName)) { TypeSyntax? declaredType = null; if (typedParent.IsParentKind(SyntaxKind.VariableDeclaration, out VariableDeclarationSyntax? varDecl)) { declaredType = varDecl.Type; } else if (typedParent.IsParentKind(SyntaxKind.FieldDeclaration, out FieldDeclarationSyntax? fieldDecl)) { declaredType = fieldDecl.Declaration.Type; } return declaredType == typedParent && typedToken.ValueText == "var"; } return false; } public bool IsTypeNamedDynamic(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent) { if (parent is ExpressionSyntax typedParent) { if (SyntaxFacts.IsInTypeOnlyContext(typedParent) && typedParent.IsKind(SyntaxKind.IdentifierName) && token.ValueText == "dynamic") { return true; } } return false; } public bool IsBindableToken(SyntaxToken token) { if (this.IsWord(token) || this.IsLiteral(token) || this.IsOperator(token)) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.DelegateKeyword: case SyntaxKind.VoidKeyword: return false; } return true; } // In the order by clause a comma might be bound to ThenBy or ThenByDescending if (token.Kind() == SyntaxKind.CommaToken && token.Parent.IsKind(SyntaxKind.OrderByClause)) { return true; } return false; } public void GetPartsOfConditionalAccessExpression( SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull) { var conditionalAccess = (ConditionalAccessExpressionSyntax)node; expression = conditionalAccess.Expression; operatorToken = conditionalAccess.OperatorToken; whenNotNull = conditionalAccess.WhenNotNull; } public bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node) => node is PostfixUnaryExpressionSyntax; public bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node) => node is MemberBindingExpressionSyntax; public bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) => (node as MemberAccessExpressionSyntax)?.Kind() == SyntaxKind.PointerMemberAccessExpression; public void GetNameAndArityOfSimpleName(SyntaxNode? node, out string? name, out int arity) { name = null; arity = 0; if (node is SimpleNameSyntax simpleName) { name = simpleName.Identifier.ValueText; arity = simpleName.Arity; } } public bool LooksGeneric(SyntaxNode simpleName) => simpleName.IsKind(SyntaxKind.GenericName) || simpleName.GetLastToken().GetNextToken().Kind() == SyntaxKind.LessThanToken; public SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node) => (node as MemberBindingExpressionSyntax).GetParentConditionalAccessExpression()?.Expression; public SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node) => ((MemberBindingExpressionSyntax)node).Name; public SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode? node, bool allowImplicitTarget) => (node as MemberAccessExpressionSyntax)?.Expression; public void GetPartsOfElementAccessExpression(SyntaxNode? node, out SyntaxNode? expression, out SyntaxNode? argumentList) { var elementAccess = node as ElementAccessExpressionSyntax; expression = elementAccess?.Expression; argumentList = elementAccess?.ArgumentList; } public SyntaxNode? GetExpressionOfInterpolation(SyntaxNode? node) => (node as InterpolationSyntax)?.Expression; public bool IsInStaticContext(SyntaxNode node) => node.IsInStaticContext(); public bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node) => SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax); public bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.BaseList); public SyntaxNode? GetExpressionOfArgument(SyntaxNode? node) => (node as ArgumentSyntax)?.Expression; public RefKind GetRefKindOfArgument(SyntaxNode? node) => (node as ArgumentSyntax).GetRefKind(); public bool IsArgument([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.Argument); public bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node) { return node is ArgumentSyntax argument && argument.RefOrOutKeyword.Kind() == SyntaxKind.None && argument.NameColon == null; } public bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsInConstantContext(); public bool IsInConstructor(SyntaxNode node) => node.GetAncestor<ConstructorDeclarationSyntax>() != null; public bool IsUnsafeContext(SyntaxNode node) => node.IsUnsafeContext(); public SyntaxNode GetNameOfAttribute(SyntaxNode node) => ((AttributeSyntax)node).Name; public SyntaxNode GetExpressionOfParenthesizedExpression(SyntaxNode node) => ((ParenthesizedExpressionSyntax)node).Expression; public bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node) => (node as IdentifierNameSyntax).IsAttributeNamedArgumentIdentifier(); public SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position) { if (root == null) { throw new ArgumentNullException(nameof(root)); } if (position < 0 || position > root.Span.End) { throw new ArgumentOutOfRangeException(nameof(position)); } return root .FindToken(position) .GetAncestors<SyntaxNode>() .FirstOrDefault(n => n is BaseTypeDeclarationSyntax || n is DelegateDeclarationSyntax); } public SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node) => throw ExceptionUtilities.Unreachable; public SyntaxToken FindTokenOnLeftOfPosition( SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments) { return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments); } public SyntaxToken FindTokenOnRightOfPosition( SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments) { return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments); } public bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.IdentifierName) && node.IsParentKind(SyntaxKind.NameColon) && node.Parent.IsParentKind(SyntaxKind.Subpattern); public bool IsPropertyPatternClause(SyntaxNode node) => node.Kind() == SyntaxKind.PropertyPatternClause; public bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node) => IsMemberInitializerNamedAssignmentIdentifier(node, out _); public bool IsMemberInitializerNamedAssignmentIdentifier( [NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance) { initializedInstance = null; if (node is IdentifierNameSyntax identifier && identifier.IsLeftSideOfAssignExpression()) { if (identifier.Parent.IsParentKind(SyntaxKind.WithInitializerExpression)) { var withInitializer = identifier.Parent.GetRequiredParent(); initializedInstance = withInitializer.GetRequiredParent(); return true; } else if (identifier.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression)) { var objectInitializer = identifier.Parent.GetRequiredParent(); if (objectInitializer.Parent is BaseObjectCreationExpressionSyntax) { initializedInstance = objectInitializer.Parent; return true; } else if (objectInitializer.IsParentKind(SyntaxKind.SimpleAssignmentExpression, out AssignmentExpressionSyntax? assignment)) { initializedInstance = assignment.Left; return true; } } } return false; } public bool IsElementAccessExpression(SyntaxNode? node) => node.IsKind(SyntaxKind.ElementAccessExpression); [return: NotNullIfNotNull("node")] public SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false) => node.ConvertToSingleLine(useElasticTrivia); public void GetPartsOfParenthesizedExpression( SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen) { var parenthesizedExpression = (ParenthesizedExpressionSyntax)node; openParen = parenthesizedExpression.OpenParenToken; expression = parenthesizedExpression.Expression; closeParen = parenthesizedExpression.CloseParenToken; } public bool IsIndexerMemberCRef(SyntaxNode? node) => node.IsKind(SyntaxKind.IndexerMemberCref); public SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true) { Contract.ThrowIfNull(root, "root"); Contract.ThrowIfTrue(position < 0 || position > root.FullSpan.End, "position"); var end = root.FullSpan.End; if (end == 0) { // empty file return null; } // make sure position doesn't touch end of root position = Math.Min(position, end - 1); var node = root.FindToken(position).Parent; while (node != null) { if (useFullSpan || node.Span.Contains(position)) { var kind = node.Kind(); if ((kind != SyntaxKind.GlobalStatement) && (kind != SyntaxKind.IncompleteMember) && (node is MemberDeclarationSyntax)) { return node; } } node = node.Parent; } return null; } public bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node) { return node is BaseMethodDeclarationSyntax || node is BasePropertyDeclarationSyntax || node is EnumMemberDeclarationSyntax || node is BaseFieldDeclarationSyntax; } public bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node) { return node is BaseNamespaceDeclarationSyntax || node is TypeDeclarationSyntax || node is EnumDeclarationSyntax; } private const string dotToken = "."; public string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null) { if (node == null) { return string.Empty; } var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; // return type var memberDeclaration = node as MemberDeclarationSyntax; if ((options & DisplayNameOptions.IncludeType) != 0) { var type = memberDeclaration.GetMemberType(); if (type != null && !type.IsMissing) { builder.Append(type); builder.Append(' '); } } var names = ArrayBuilder<string?>.GetInstance(); // containing type(s) var parent = node.GetAncestor<TypeDeclarationSyntax>() ?? node.Parent; while (parent is TypeDeclarationSyntax) { names.Push(GetName(parent, options)); parent = parent.Parent; } // containing namespace(s) in source (if any) if ((options & DisplayNameOptions.IncludeNamespaces) != 0) { while (parent is BaseNamespaceDeclarationSyntax) { names.Add(GetName(parent, options)); parent = parent.Parent; } } while (!names.IsEmpty()) { var name = names.Pop(); if (name != null) { builder.Append(name); builder.Append(dotToken); } } // name (including generic type parameters) builder.Append(GetName(node, options)); // parameter list (if any) if ((options & DisplayNameOptions.IncludeParameters) != 0) { builder.Append(memberDeclaration.GetParameterList()); } return pooled.ToStringAndFree(); } private static string? GetName(SyntaxNode node, DisplayNameOptions options) { const string missingTokenPlaceholder = "?"; switch (node.Kind()) { case SyntaxKind.CompilationUnit: return null; case SyntaxKind.IdentifierName: var identifier = ((IdentifierNameSyntax)node).Identifier; return identifier.IsMissing ? missingTokenPlaceholder : identifier.Text; case SyntaxKind.IncompleteMember: return missingTokenPlaceholder; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return GetName(((BaseNamespaceDeclarationSyntax)node).Name, options); case SyntaxKind.QualifiedName: var qualified = (QualifiedNameSyntax)node; return GetName(qualified.Left, options) + dotToken + GetName(qualified.Right, options); } string? name = null; if (node is MemberDeclarationSyntax memberDeclaration) { if (memberDeclaration.Kind() == SyntaxKind.ConversionOperatorDeclaration) { name = (memberDeclaration as ConversionOperatorDeclarationSyntax)?.Type.ToString(); } else { var nameToken = memberDeclaration.GetNameToken(); if (nameToken != default) { name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text; if (memberDeclaration.Kind() == SyntaxKind.DestructorDeclaration) { name = "~" + name; } if ((options & DisplayNameOptions.IncludeTypeParameters) != 0) { var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; builder.Append(name); AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList()); name = pooled.ToStringAndFree(); } } else { Debug.Assert(memberDeclaration.Kind() == SyntaxKind.IncompleteMember); name = "?"; } } } else { if (node is VariableDeclaratorSyntax fieldDeclarator) { var nameToken = fieldDeclarator.Identifier; if (nameToken != default) { name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text; } } } Debug.Assert(name != null, "Unexpected node type " + node.Kind()); return name; } private static void AppendTypeParameterList(StringBuilder builder, TypeParameterListSyntax typeParameterList) { if (typeParameterList != null && typeParameterList.Parameters.Count > 0) { builder.Append('<'); builder.Append(typeParameterList.Parameters[0].Identifier.ValueText); for (var i = 1; i < typeParameterList.Parameters.Count; i++) { builder.Append(", "); builder.Append(typeParameterList.Parameters[i].Identifier.ValueText); } builder.Append('>'); } } public List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root) { var list = new List<SyntaxNode>(); AppendMembers(root, list, topLevel: true, methodLevel: true); return list; } public List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root) { var list = new List<SyntaxNode>(); AppendMembers(root, list, topLevel: false, methodLevel: true); return list; } public bool IsClassDeclaration([NotNullWhen(true)] SyntaxNode? node) => node?.Kind() == SyntaxKind.ClassDeclaration; public bool IsNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node) => node is BaseNamespaceDeclarationSyntax; public SyntaxNode? GetNameOfNamespaceDeclaration(SyntaxNode? node) => (node as BaseNamespaceDeclarationSyntax)?.Name; public SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration) => ((TypeDeclarationSyntax)typeDeclaration).Members; public SyntaxList<SyntaxNode> GetMembersOfNamespaceDeclaration(SyntaxNode namespaceDeclaration) => ((BaseNamespaceDeclarationSyntax)namespaceDeclaration).Members; public SyntaxList<SyntaxNode> GetMembersOfCompilationUnit(SyntaxNode compilationUnit) => ((CompilationUnitSyntax)compilationUnit).Members; public SyntaxList<SyntaxNode> GetImportsOfNamespaceDeclaration(SyntaxNode namespaceDeclaration) => ((BaseNamespaceDeclarationSyntax)namespaceDeclaration).Usings; public SyntaxList<SyntaxNode> GetImportsOfCompilationUnit(SyntaxNode compilationUnit) => ((CompilationUnitSyntax)compilationUnit).Usings; private void AppendMembers(SyntaxNode? node, List<SyntaxNode> list, bool topLevel, bool methodLevel) { Debug.Assert(topLevel || methodLevel); foreach (var member in node.GetMembers()) { if (IsTopLevelNodeWithMembers(member)) { if (topLevel) { list.Add(member); } AppendMembers(member, list, topLevel, methodLevel); continue; } if (methodLevel && IsMethodLevelMember(member)) { list.Add(member); } } } public TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node) { if (node.Span.IsEmpty) { return default; } var member = GetContainingMemberDeclaration(node, node.SpanStart); if (member == null) { return default; } // TODO: currently we only support method for now if (member is BaseMethodDeclarationSyntax method) { if (method.Body == null) { return default; } return GetBlockBodySpan(method.Body); } return default; } public bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span) { switch (node) { case ConstructorDeclarationSyntax constructor: return (constructor.Body != null && GetBlockBodySpan(constructor.Body).Contains(span)) || (constructor.Initializer != null && constructor.Initializer.Span.Contains(span)); case BaseMethodDeclarationSyntax method: return method.Body != null && GetBlockBodySpan(method.Body).Contains(span); case BasePropertyDeclarationSyntax property: return property.AccessorList != null && property.AccessorList.Span.Contains(span); case EnumMemberDeclarationSyntax @enum: return @enum.EqualsValue != null && @enum.EqualsValue.Span.Contains(span); case BaseFieldDeclarationSyntax field: return field.Declaration != null && field.Declaration.Span.Contains(span); } return false; } private static TextSpan GetBlockBodySpan(BlockSyntax body) => TextSpan.FromBounds(body.OpenBraceToken.Span.End, body.CloseBraceToken.SpanStart); public SyntaxNode? TryGetBindableParent(SyntaxToken token) { var node = token.Parent; while (node != null) { var parent = node.Parent; // If this node is on the left side of a member access expression, don't ascend // further or we'll end up binding to something else. if (parent is MemberAccessExpressionSyntax memberAccess) { if (memberAccess.Expression == node) { break; } } // If this node is on the left side of a qualified name, don't ascend // further or we'll end up binding to something else. if (parent is QualifiedNameSyntax qualifiedName) { if (qualifiedName.Left == node) { break; } } // If this node is on the left side of a alias-qualified name, don't ascend // further or we'll end up binding to something else. if (parent is AliasQualifiedNameSyntax aliasQualifiedName) { if (aliasQualifiedName.Alias == node) { break; } } // If this node is the type of an object creation expression, return the // object creation expression. if (parent is ObjectCreationExpressionSyntax objectCreation) { if (objectCreation.Type == node) { node = parent; break; } } // The inside of an interpolated string is treated as its own token so we // need to force navigation to the parent expression syntax. if (node is InterpolatedStringTextSyntax && parent is InterpolatedStringExpressionSyntax) { node = parent; break; } // If this node is not parented by a name, we're done. if (!(parent is NameSyntax)) { break; } node = parent; } if (node is VarPatternSyntax) { return node; } // Patterns are never bindable (though their constituent types/exprs may be). return node is PatternSyntax ? null : node; } public IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken) { if (!(root is CompilationUnitSyntax compilationUnit)) { return SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } var constructors = new List<SyntaxNode>(); AppendConstructors(compilationUnit.Members, constructors, cancellationToken); return constructors; } private void AppendConstructors(SyntaxList<MemberDeclarationSyntax> members, List<SyntaxNode> constructors, CancellationToken cancellationToken) { foreach (var member in members) { cancellationToken.ThrowIfCancellationRequested(); switch (member) { case ConstructorDeclarationSyntax constructor: constructors.Add(constructor); continue; case BaseNamespaceDeclarationSyntax @namespace: AppendConstructors(@namespace.Members, constructors, cancellationToken); break; case ClassDeclarationSyntax @class: AppendConstructors(@class.Members, constructors, cancellationToken); break; case RecordDeclarationSyntax record: AppendConstructors(record.Members, constructors, cancellationToken); break; case StructDeclarationSyntax @struct: AppendConstructors(@struct.Members, constructors, cancellationToken); break; } } } public bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace) { if (token.Kind() == SyntaxKind.CloseBraceToken) { var tuple = token.Parent.GetBraces(); openBrace = tuple.openBrace; return openBrace.Kind() == SyntaxKind.OpenBraceToken; } openBrace = default; return false; } public TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position, findInsideTrivia: false); if (trivia.Kind() == SyntaxKind.DisabledTextTrivia) { return trivia.FullSpan; } var token = syntaxTree.FindTokenOrEndToken(position, cancellationToken); if (token.Kind() == SyntaxKind.EndOfFileToken) { var triviaList = token.LeadingTrivia; foreach (var triviaTok in triviaList.Reverse()) { if (triviaTok.Span.Contains(position)) { return default; } if (triviaTok.Span.End < position) { if (!triviaTok.HasStructure) { return default; } var structure = triviaTok.GetStructure(); if (structure is BranchingDirectiveTriviaSyntax branch) { return !branch.IsActive || !branch.BranchTaken ? TextSpan.FromBounds(branch.FullSpan.Start, position) : default; } } } } return default; } public string GetNameForArgument(SyntaxNode? argument) => (argument as ArgumentSyntax)?.NameColon?.Name.Identifier.ValueText ?? string.Empty; public string GetNameForAttributeArgument(SyntaxNode? argument) => (argument as AttributeArgumentSyntax)?.NameEquals?.Name.Identifier.ValueText ?? string.Empty; public bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfDot(); public SyntaxNode? GetRightSideOfDot(SyntaxNode? node) { return (node as QualifiedNameSyntax)?.Right ?? (node as MemberAccessExpressionSyntax)?.Name; } public SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget) { return (node as QualifiedNameSyntax)?.Left ?? (node as MemberAccessExpressionSyntax)?.Expression; } public bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node) => (node as NameSyntax).IsLeftSideOfExplicitInterfaceSpecifier(); public bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfAssignExpression(); public bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfAnyAssignExpression(); public bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfCompoundAssignExpression(); public SyntaxNode? GetRightHandSideOfAssignment(SyntaxNode? node) => (node as AssignmentExpressionSyntax)?.Right; public bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.AnonymousObjectMemberDeclarator, out AnonymousObjectMemberDeclaratorSyntax? anonObject) && anonObject.NameEquals == null; public bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.PostIncrementExpression) || node.IsParentKind(SyntaxKind.PreIncrementExpression); public static bool IsOperandOfDecrementExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.PostDecrementExpression) || node.IsParentKind(SyntaxKind.PreDecrementExpression); public bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node) => IsOperandOfIncrementExpression(node) || IsOperandOfDecrementExpression(node); public SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString) => ((InterpolatedStringExpressionSyntax)interpolatedString).Contents; public bool IsVerbatimStringLiteral(SyntaxToken token) => token.IsVerbatimStringLiteral(); public bool IsNumericLiteral(SyntaxToken token) => token.Kind() == SyntaxKind.NumericLiteralToken; public void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList) { var invocation = (InvocationExpressionSyntax)node; expression = invocation.Expression; argumentList = invocation.ArgumentList; } public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode? invocationExpression) => GetArgumentsOfArgumentList((invocationExpression as InvocationExpressionSyntax)?.ArgumentList); public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode? objectCreationExpression) => GetArgumentsOfArgumentList((objectCreationExpression as BaseObjectCreationExpressionSyntax)?.ArgumentList); public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode? argumentList) => (argumentList as BaseArgumentListSyntax)?.Arguments ?? default; public SyntaxNode GetArgumentListOfInvocationExpression(SyntaxNode invocationExpression) => ((InvocationExpressionSyntax)invocationExpression).ArgumentList; public SyntaxNode? GetArgumentListOfObjectCreationExpression(SyntaxNode objectCreationExpression) => ((ObjectCreationExpressionSyntax)objectCreationExpression)!.ArgumentList; public bool IsRegularComment(SyntaxTrivia trivia) => trivia.IsRegularComment(); public bool IsDocumentationComment(SyntaxTrivia trivia) => trivia.IsDocComment(); public bool IsElastic(SyntaxTrivia trivia) => trivia.IsElastic(); public bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes) => trivia.IsPragmaDirective(out isDisable, out isActive, out errorCodes); public bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.DocumentationCommentExteriorTrivia; public bool IsDocumentationComment(SyntaxNode node) => SyntaxFacts.IsDocumentationCommentTrivia(node.Kind()); public bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node) { return node.IsKind(SyntaxKind.UsingDirective) || node.IsKind(SyntaxKind.ExternAliasDirective); } public bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node) => IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword); public bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node) => IsGlobalAttribute(node, SyntaxKind.ModuleKeyword); private static bool IsGlobalAttribute([NotNullWhen(true)] SyntaxNode? node, SyntaxKind attributeTarget) => node.IsKind(SyntaxKind.Attribute) && node.Parent.IsKind(SyntaxKind.AttributeList, out AttributeListSyntax? attributeList) && attributeList.Target?.Identifier.Kind() == attributeTarget; private static bool IsMemberDeclaration(SyntaxNode node) { // From the C# language spec: // class-member-declaration: // constant-declaration // field-declaration // method-declaration // property-declaration // event-declaration // indexer-declaration // operator-declaration // constructor-declaration // destructor-declaration // static-constructor-declaration // type-declaration switch (node.Kind()) { // Because fields declarations can define multiple symbols "public int a, b;" // We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name. case SyntaxKind.VariableDeclarator: return node.Parent.IsParentKind(SyntaxKind.FieldDeclaration) || node.Parent.IsParentKind(SyntaxKind.EventFieldDeclaration); case SyntaxKind.FieldDeclaration: case SyntaxKind.MethodDeclaration: case SyntaxKind.PropertyDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: return true; default: return false; } } public bool IsDeclaration(SyntaxNode node) => SyntaxFacts.IsNamespaceMemberDeclaration(node.Kind()) || IsMemberDeclaration(node); public bool IsTypeDeclaration(SyntaxNode node) => SyntaxFacts.IsTypeDeclaration(node.Kind()); public SyntaxNode? GetObjectCreationInitializer(SyntaxNode node) => ((ObjectCreationExpressionSyntax)node).Initializer; public SyntaxNode GetObjectCreationType(SyntaxNode node) => ((ObjectCreationExpressionSyntax)node).Type; public bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement) => statement.IsKind(SyntaxKind.ExpressionStatement, out ExpressionStatementSyntax? exprStatement) && exprStatement.Expression.IsKind(SyntaxKind.SimpleAssignmentExpression); public void GetPartsOfAssignmentStatement( SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { GetPartsOfAssignmentExpressionOrStatement( ((ExpressionStatementSyntax)statement).Expression, out left, out operatorToken, out right); } public void GetPartsOfAssignmentExpressionOrStatement( SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var expression = statement; if (statement is ExpressionStatementSyntax expressionStatement) { expression = expressionStatement.Expression; } var assignment = (AssignmentExpressionSyntax)expression; left = assignment.Left; operatorToken = assignment.OperatorToken; right = assignment.Right; } public SyntaxNode GetNameOfMemberAccessExpression(SyntaxNode memberAccessExpression) => ((MemberAccessExpressionSyntax)memberAccessExpression).Name; public void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name) { var memberAccess = (MemberAccessExpressionSyntax)node; expression = memberAccess.Expression; operatorToken = memberAccess.OperatorToken; name = memberAccess.Name; } public SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node) => ((SimpleNameSyntax)node).Identifier; public SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node) => ((VariableDeclaratorSyntax)node).Identifier; public SyntaxToken GetIdentifierOfParameter(SyntaxNode node) => ((ParameterSyntax)node).Identifier; public SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node) => ((IdentifierNameSyntax)node).Identifier; public bool IsLocalFunctionStatement([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.LocalFunctionStatement); public bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement) { return ((LocalDeclarationStatementSyntax)localDeclarationStatement).Declaration.Variables.Contains( (VariableDeclaratorSyntax)declarator); } public bool AreEquivalent(SyntaxToken token1, SyntaxToken token2) => SyntaxFactory.AreEquivalent(token1, token2); public bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2) => SyntaxFactory.AreEquivalent(node1, node2); public bool IsExpressionOfInvocationExpression([NotNullWhen(true)] SyntaxNode? node) => (node?.Parent as InvocationExpressionSyntax)?.Expression == node; public bool IsExpressionOfAwaitExpression([NotNullWhen(true)] SyntaxNode? node) => (node?.Parent as AwaitExpressionSyntax)?.Expression == node; public bool IsExpressionOfMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) => (node?.Parent as MemberAccessExpressionSyntax)?.Expression == node; public static SyntaxNode GetExpressionOfInvocationExpression(SyntaxNode node) => ((InvocationExpressionSyntax)node).Expression; public SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node) => ((AwaitExpressionSyntax)node).Expression; public bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node) => node?.Parent is ForEachStatementSyntax foreachStatement && foreachStatement.Expression == node; public SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node) => ((ExpressionStatementSyntax)node).Expression; public bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node) => node is BinaryExpressionSyntax; public bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.IsExpression); public void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var binaryExpression = (BinaryExpressionSyntax)node; left = binaryExpression.Left; operatorToken = binaryExpression.OperatorToken; right = binaryExpression.Right; } public void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse) { var conditionalExpression = (ConditionalExpressionSyntax)node; condition = conditionalExpression.Condition; whenTrue = conditionalExpression.WhenTrue; whenFalse = conditionalExpression.WhenFalse; } [return: NotNullIfNotNull("node")] public SyntaxNode? WalkDownParentheses(SyntaxNode? node) => (node as ExpressionSyntax)?.WalkDownParentheses() ?? node; public void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node, out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode { var tupleExpression = (TupleExpressionSyntax)node; openParen = tupleExpression.OpenParenToken; arguments = (SeparatedSyntaxList<TArgumentSyntax>)(SeparatedSyntaxList<SyntaxNode>)tupleExpression.Arguments; closeParen = tupleExpression.CloseParenToken; } public SyntaxNode GetOperandOfPrefixUnaryExpression(SyntaxNode node) => ((PrefixUnaryExpressionSyntax)node).Operand; public SyntaxToken GetOperatorTokenOfPrefixUnaryExpression(SyntaxNode node) => ((PrefixUnaryExpressionSyntax)node).OperatorToken; public SyntaxNode? GetNextExecutableStatement(SyntaxNode statement) => ((StatementSyntax)statement).GetNextStatement(); public override bool IsSingleLineCommentTrivia(SyntaxTrivia trivia) => trivia.IsSingleLineComment(); public override bool IsMultiLineCommentTrivia(SyntaxTrivia trivia) => trivia.IsMultiLineComment(); public override bool IsSingleLineDocCommentTrivia(SyntaxTrivia trivia) => trivia.IsSingleLineDocComment(); public override bool IsMultiLineDocCommentTrivia(SyntaxTrivia trivia) => trivia.IsMultiLineDocComment(); public override bool IsShebangDirectiveTrivia(SyntaxTrivia trivia) => trivia.IsShebangDirective(); public override bool IsPreprocessorDirective(SyntaxTrivia trivia) => SyntaxFacts.IsPreprocessorDirective(trivia.Kind()); public bool IsOnTypeHeader(SyntaxNode root, int position, bool fullHeader, [NotNullWhen(true)] out SyntaxNode? typeDeclaration) { var node = TryGetAncestorForLocation<BaseTypeDeclarationSyntax>(root, position); typeDeclaration = node; if (node == null) return false; var lastToken = (node as TypeDeclarationSyntax)?.TypeParameterList?.GetLastToken() ?? node.Identifier; if (fullHeader) lastToken = node.BaseList?.GetLastToken() ?? lastToken; return IsOnHeader(root, position, node, lastToken); } public bool IsOnPropertyDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? propertyDeclaration) { var node = TryGetAncestorForLocation<PropertyDeclarationSyntax>(root, position); propertyDeclaration = node; if (propertyDeclaration == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.Identifier); } public bool IsOnParameterHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? parameter) { var node = TryGetAncestorForLocation<ParameterSyntax>(root, position); parameter = node; if (parameter == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node); } public bool IsOnMethodHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? method) { var node = TryGetAncestorForLocation<MethodDeclarationSyntax>(root, position); method = node; if (method == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.ParameterList); } public bool IsOnLocalFunctionHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localFunction) { var node = TryGetAncestorForLocation<LocalFunctionStatementSyntax>(root, position); localFunction = node; if (localFunction == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.ParameterList); } public bool IsOnLocalDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localDeclaration) { var node = TryGetAncestorForLocation<LocalDeclarationStatementSyntax>(root, position); localDeclaration = node; if (localDeclaration == null) { return false; } var initializersExpressions = node!.Declaration.Variables .Where(v => v.Initializer != null) .SelectAsArray(initializedV => initializedV.Initializer!.Value); return IsOnHeader(root, position, node, node, holes: initializersExpressions); } public bool IsOnIfStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? ifStatement) { var node = TryGetAncestorForLocation<IfStatementSyntax>(root, position); ifStatement = node; if (ifStatement == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.CloseParenToken); } public bool IsOnWhileStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? whileStatement) { var node = TryGetAncestorForLocation<WhileStatementSyntax>(root, position); whileStatement = node; if (whileStatement == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.CloseParenToken); } public bool IsOnForeachHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? foreachStatement) { var node = TryGetAncestorForLocation<ForEachStatementSyntax>(root, position); foreachStatement = node; if (foreachStatement == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.CloseParenToken); } public bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration) { var token = root.FindToken(position); var typeDecl = token.GetAncestor<TypeDeclarationSyntax>(); typeDeclaration = typeDecl; if (typeDecl == null) { return false; } RoslynDebug.AssertNotNull(typeDeclaration); if (position < typeDecl.OpenBraceToken.Span.End || position > typeDecl.CloseBraceToken.Span.Start) { return false; } var line = sourceText.Lines.GetLineFromPosition(position); if (!line.IsEmptyOrWhitespace()) { return false; } var member = typeDecl.Members.FirstOrDefault(d => d.FullSpan.Contains(position)); if (member == null) { // 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) { foreach (var trivia in member.GetLeadingTrivia()) { if (!trivia.IsWhitespaceOrEndOfLine()) { return false; } if (trivia.FullSpan.Contains(position)) { return true; } } } } return false; } protected override bool ContainsInterleavedDirective(TextSpan span, SyntaxToken token, CancellationToken cancellationToken) => token.ContainsInterleavedDirective(span, cancellationToken); public SyntaxTokenList GetModifiers(SyntaxNode? node) => node.GetModifiers(); public SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers) => node.WithModifiers(modifiers); public bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node) => node is LiteralExpressionSyntax; public SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node) => ((LocalDeclarationStatementSyntax)node).Declaration.Variables; public SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node) => ((VariableDeclaratorSyntax)node).Initializer; public SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node) => ((VariableDeclarationSyntax)((VariableDeclaratorSyntax)node).Parent!).Type; public SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node) => ((EqualsValueClauseSyntax?)node)?.Value; public bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.Block); public bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.Block, SyntaxKind.SwitchSection, SyntaxKind.CompilationUnit); public IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node) { return node switch { BlockSyntax block => block.Statements, SwitchSectionSyntax switchSection => switchSection.Statements, CompilationUnitSyntax compilationUnit => compilationUnit.Members.OfType<GlobalStatementSyntax>().SelectAsArray(globalStatement => globalStatement.Statement), _ => throw ExceptionUtilities.UnexpectedValue(node), }; } public SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes) => nodes.FindInnermostCommonNode(node => IsExecutableBlock(node)); public bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node) => IsExecutableBlock(node) || node.IsEmbeddedStatementOwner(); public IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node) { if (IsExecutableBlock(node)) return GetExecutableBlockStatements(node); else if (node.GetEmbeddedStatement() is { } embeddedStatement) return ImmutableArray.Create<SyntaxNode>(embeddedStatement); else return ImmutableArray<SyntaxNode>.Empty; } public bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node) => node is CastExpressionSyntax; public bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node) => node is CastExpressionSyntax; public void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression) { var cast = (CastExpressionSyntax)node; type = cast.Type; expression = cast.Expression; } public SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token) { if (token.Kind() == SyntaxKind.OverrideKeyword && token.Parent is MemberDeclarationSyntax member) { return member.GetNameToken(); } return null; } public override SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node) => node.GetAttributeLists(); public override bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.XmlElement, out XmlElementSyntax? xmlElement) && xmlElement.StartTag.Name.LocalName.ValueText == DocumentationCommentXmlNames.ParameterElementName; public override SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia) { if (trivia.GetStructure() is DocumentationCommentTriviaSyntax documentationCommentTrivia) { return documentationCommentTrivia.Content; } throw ExceptionUtilities.UnexpectedValue(trivia.Kind()); } public override bool CanHaveAccessibility(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.DelegateDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return true; case SyntaxKind.VariableDeclaration: case SyntaxKind.VariableDeclarator: var declarationKind = this.GetDeclarationKind(declaration); return declarationKind == DeclarationKind.Field || declarationKind == DeclarationKind.Event; case SyntaxKind.ConstructorDeclaration: // Static constructor can't have accessibility return !((ConstructorDeclarationSyntax)declaration).Modifiers.Any(SyntaxKind.StaticKeyword); case SyntaxKind.PropertyDeclaration: return ((PropertyDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null; case SyntaxKind.IndexerDeclaration: return ((IndexerDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)declaration; if (method.ExplicitInterfaceSpecifier != null) { // explicit interface methods can't have accessibility. return false; } if (method.Modifiers.Any(SyntaxKind.PartialKeyword)) { // partial methods can't have accessibility modifiers. return false; } return true; case SyntaxKind.EventDeclaration: return ((EventDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null; default: return false; } } public override Accessibility GetAccessibility(SyntaxNode declaration) { if (!CanHaveAccessibility(declaration)) { return Accessibility.NotApplicable; } var modifierTokens = GetModifierTokens(declaration); GetAccessibilityAndModifiers(modifierTokens, out var accessibility, out _, out _); return accessibility; } public override void GetAccessibilityAndModifiers(SyntaxTokenList modifierList, out Accessibility accessibility, out DeclarationModifiers modifiers, out bool isDefault) { accessibility = Accessibility.NotApplicable; modifiers = DeclarationModifiers.None; isDefault = false; foreach (var token in modifierList) { accessibility = (token.Kind(), accessibility) switch { (SyntaxKind.PublicKeyword, _) => Accessibility.Public, (SyntaxKind.PrivateKeyword, Accessibility.Protected) => Accessibility.ProtectedAndInternal, (SyntaxKind.PrivateKeyword, _) => Accessibility.Private, (SyntaxKind.InternalKeyword, Accessibility.Protected) => Accessibility.ProtectedOrInternal, (SyntaxKind.InternalKeyword, _) => Accessibility.Internal, (SyntaxKind.ProtectedKeyword, Accessibility.Private) => Accessibility.ProtectedAndInternal, (SyntaxKind.ProtectedKeyword, Accessibility.Internal) => Accessibility.ProtectedOrInternal, (SyntaxKind.ProtectedKeyword, _) => Accessibility.Protected, _ => accessibility, }; modifiers |= token.Kind() switch { SyntaxKind.AbstractKeyword => DeclarationModifiers.Abstract, SyntaxKind.NewKeyword => DeclarationModifiers.New, SyntaxKind.OverrideKeyword => DeclarationModifiers.Override, SyntaxKind.VirtualKeyword => DeclarationModifiers.Virtual, SyntaxKind.StaticKeyword => DeclarationModifiers.Static, SyntaxKind.AsyncKeyword => DeclarationModifiers.Async, SyntaxKind.ConstKeyword => DeclarationModifiers.Const, SyntaxKind.ReadOnlyKeyword => DeclarationModifiers.ReadOnly, SyntaxKind.SealedKeyword => DeclarationModifiers.Sealed, SyntaxKind.UnsafeKeyword => DeclarationModifiers.Unsafe, SyntaxKind.PartialKeyword => DeclarationModifiers.Partial, SyntaxKind.RefKeyword => DeclarationModifiers.Ref, SyntaxKind.VolatileKeyword => DeclarationModifiers.Volatile, SyntaxKind.ExternKeyword => DeclarationModifiers.Extern, _ => DeclarationModifiers.None, }; isDefault |= token.Kind() == SyntaxKind.DefaultKeyword; } } public override SyntaxTokenList GetModifierTokens(SyntaxNode? declaration) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.Modifiers, ParameterSyntax parameter => parameter.Modifiers, LocalDeclarationStatementSyntax localDecl => localDecl.Modifiers, LocalFunctionStatementSyntax localFunc => localFunc.Modifiers, AccessorDeclarationSyntax accessor => accessor.Modifiers, VariableDeclarationSyntax varDecl => GetModifierTokens(varDecl.Parent), VariableDeclaratorSyntax varDecl => GetModifierTokens(varDecl.Parent), AnonymousFunctionExpressionSyntax anonymous => anonymous.Modifiers, _ => default, }; public override DeclarationKind GetDeclarationKind(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: return DeclarationKind.Class; case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: return DeclarationKind.Struct; case SyntaxKind.InterfaceDeclaration: return DeclarationKind.Interface; case SyntaxKind.EnumDeclaration: return DeclarationKind.Enum; case SyntaxKind.DelegateDeclaration: return DeclarationKind.Delegate; case SyntaxKind.MethodDeclaration: return DeclarationKind.Method; case SyntaxKind.OperatorDeclaration: return DeclarationKind.Operator; case SyntaxKind.ConversionOperatorDeclaration: return DeclarationKind.ConversionOperator; case SyntaxKind.ConstructorDeclaration: return DeclarationKind.Constructor; case SyntaxKind.DestructorDeclaration: return DeclarationKind.Destructor; case SyntaxKind.PropertyDeclaration: return DeclarationKind.Property; case SyntaxKind.IndexerDeclaration: return DeclarationKind.Indexer; case SyntaxKind.EventDeclaration: return DeclarationKind.CustomEvent; case SyntaxKind.EnumMemberDeclaration: return DeclarationKind.EnumMember; case SyntaxKind.CompilationUnit: return DeclarationKind.CompilationUnit; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return DeclarationKind.Namespace; case SyntaxKind.UsingDirective: return DeclarationKind.NamespaceImport; case SyntaxKind.Parameter: return DeclarationKind.Parameter; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: return DeclarationKind.LambdaExpression; case SyntaxKind.FieldDeclaration: var fd = (FieldDeclarationSyntax)declaration; if (fd.Declaration != null && fd.Declaration.Variables.Count == 1) { // this node is considered the declaration if it contains only one variable. return DeclarationKind.Field; } else { return DeclarationKind.None; } case SyntaxKind.EventFieldDeclaration: var ef = (EventFieldDeclarationSyntax)declaration; if (ef.Declaration != null && ef.Declaration.Variables.Count == 1) { // this node is considered the declaration if it contains only one variable. return DeclarationKind.Event; } else { return DeclarationKind.None; } case SyntaxKind.LocalDeclarationStatement: var ld = (LocalDeclarationStatementSyntax)declaration; if (ld.Declaration != null && ld.Declaration.Variables.Count == 1) { // this node is considered the declaration if it contains only one variable. return DeclarationKind.Variable; } else { return DeclarationKind.None; } case SyntaxKind.VariableDeclaration: { var vd = (VariableDeclarationSyntax)declaration; if (vd.Variables.Count == 1 && vd.Parent == null) { // this node is the declaration if it contains only one variable and has no parent. return DeclarationKind.Variable; } else { return DeclarationKind.None; } } case SyntaxKind.VariableDeclarator: { var vd = declaration.Parent as VariableDeclarationSyntax; // this node is considered the declaration if it is one among many, or it has no parent if (vd == null || vd.Variables.Count > 1) { if (ParentIsFieldDeclaration(vd)) { return DeclarationKind.Field; } else if (ParentIsEventFieldDeclaration(vd)) { return DeclarationKind.Event; } else { return DeclarationKind.Variable; } } break; } case SyntaxKind.AttributeList: var list = (AttributeListSyntax)declaration; if (list.Attributes.Count == 1) { return DeclarationKind.Attribute; } break; case SyntaxKind.Attribute: if (!(declaration.Parent is AttributeListSyntax parentList) || parentList.Attributes.Count > 1) { return DeclarationKind.Attribute; } break; case SyntaxKind.GetAccessorDeclaration: return DeclarationKind.GetAccessor; case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: return DeclarationKind.SetAccessor; case SyntaxKind.AddAccessorDeclaration: return DeclarationKind.AddAccessor; case SyntaxKind.RemoveAccessorDeclaration: return DeclarationKind.RemoveAccessor; } return DeclarationKind.None; } internal static bool ParentIsFieldDeclaration([NotNullWhen(true)] SyntaxNode? node) => node?.Parent.IsKind(SyntaxKind.FieldDeclaration) ?? false; internal static bool ParentIsEventFieldDeclaration([NotNullWhen(true)] SyntaxNode? node) => node?.Parent.IsKind(SyntaxKind.EventFieldDeclaration) ?? false; internal static bool ParentIsLocalDeclarationStatement([NotNullWhen(true)] SyntaxNode? node) => node?.Parent.IsKind(SyntaxKind.LocalDeclarationStatement) ?? false; public bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.IsPatternExpression); public void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right) { var isPatternExpression = (IsPatternExpressionSyntax)node; left = isPatternExpression.Expression; isToken = isPatternExpression.IsKeyword; right = isPatternExpression.Pattern; } public bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node) => node is PatternSyntax; public bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ConstantPattern); public bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.DeclarationPattern); public bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.RecursivePattern); public bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.VarPattern); public SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node) => ((ConstantPatternSyntax)node).Expression; public void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation) { var declarationPattern = (DeclarationPatternSyntax)node; type = declarationPattern.Type; designation = declarationPattern.Designation; } public void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation) { var recursivePattern = (RecursivePatternSyntax)node; type = recursivePattern.Type; positionalPart = recursivePattern.PositionalPatternClause; propertyPart = recursivePattern.PropertyPatternClause; designation = recursivePattern.Designation; } public bool SupportsNotPattern(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion.IsCSharp9OrAbove(); public bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.AndPattern); public bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node) => node is BinaryPatternSyntax; public bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.NotPattern); public bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.OrPattern); public bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ParenthesizedPattern); public bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.TypePattern); public bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node) => node is UnaryPatternSyntax; public void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen) { var parenthesizedPattern = (ParenthesizedPatternSyntax)node; openParen = parenthesizedPattern.OpenParenToken; pattern = parenthesizedPattern.Pattern; closeParen = parenthesizedPattern.CloseParenToken; } public void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var binaryPattern = (BinaryPatternSyntax)node; left = binaryPattern.Left; operatorToken = binaryPattern.OperatorToken; right = binaryPattern.Right; } public void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern) { var unaryPattern = (UnaryPatternSyntax)node; operatorToken = unaryPattern.OperatorToken; pattern = unaryPattern.Pattern; } public SyntaxNode GetTypeOfTypePattern(SyntaxNode node) => ((TypePatternSyntax)node).Type; public bool IsImplicitObjectCreation([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ImplicitObjectCreationExpression); public SyntaxNode GetExpressionOfThrowExpression(SyntaxNode throwExpression) => ((ThrowExpressionSyntax)throwExpression).Expression; public bool IsThrowStatement([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ThrowStatement); public bool IsLocalFunction([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.LocalFunctionStatement); public void GetPartsOfInterpolationExpression(SyntaxNode node, out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken) { var interpolatedStringExpression = (InterpolatedStringExpressionSyntax)node; stringStartToken = interpolatedStringExpression.StringStartToken; contents = interpolatedStringExpression.Contents; stringEndToken = interpolatedStringExpression.StringEndToken; } public bool IsVerbatimInterpolatedStringExpression(SyntaxNode node) => node is InterpolatedStringExpressionSyntax interpolatedString && interpolatedString.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken); } }
1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/SignatureHelp/SignatureHelpUtilities.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { internal static class SignatureHelpUtilities { private static readonly Func<BaseArgumentListSyntax, SyntaxToken> s_getBaseArgumentListOpenToken = list => list.GetOpenToken(); private static readonly Func<TypeArgumentListSyntax, SyntaxToken> s_getTypeArgumentListOpenToken = list => list.LessThanToken; private static readonly Func<InitializerExpressionSyntax, SyntaxToken> s_getInitializerExpressionOpenToken = e => e.OpenBraceToken; private static readonly Func<AttributeArgumentListSyntax, SyntaxToken> s_getAttributeArgumentListOpenToken = list => list.OpenParenToken; private static readonly Func<BaseArgumentListSyntax, SyntaxToken> s_getBaseArgumentListCloseToken = list => list.GetCloseToken(); private static readonly Func<TypeArgumentListSyntax, SyntaxToken> s_getTypeArgumentListCloseToken = list => list.GreaterThanToken; private static readonly Func<InitializerExpressionSyntax, SyntaxToken> s_getInitializerExpressionCloseToken = e => e.CloseBraceToken; private static readonly Func<AttributeArgumentListSyntax, SyntaxToken> s_getAttributeArgumentListCloseToken = list => list.CloseParenToken; private static readonly Func<BaseArgumentListSyntax, IEnumerable<SyntaxNodeOrToken>> s_getBaseArgumentListArgumentsWithSeparators = list => list.Arguments.GetWithSeparators(); private static readonly Func<TypeArgumentListSyntax, IEnumerable<SyntaxNodeOrToken>> s_getTypeArgumentListArgumentsWithSeparators = list => list.Arguments.GetWithSeparators(); private static readonly Func<InitializerExpressionSyntax, IEnumerable<SyntaxNodeOrToken>> s_getInitializerExpressionArgumentsWithSeparators = e => e.Expressions.GetWithSeparators(); private static readonly Func<AttributeArgumentListSyntax, IEnumerable<SyntaxNodeOrToken>> s_getAttributeArgumentListArgumentsWithSeparators = list => list.Arguments.GetWithSeparators(); private static readonly Func<BaseArgumentListSyntax, IEnumerable<string?>> s_getBaseArgumentListNames = list => list.Arguments.Select(argument => argument.NameColon?.Name.Identifier.ValueText); private static readonly Func<TypeArgumentListSyntax, IEnumerable<string?>> s_getTypeArgumentListNames = list => list.Arguments.Select(a => (string?)null); private static readonly Func<InitializerExpressionSyntax, IEnumerable<string?>> s_getInitializerExpressionNames = e => e.Expressions.Select(a => (string?)null); private static readonly Func<AttributeArgumentListSyntax, IEnumerable<string?>> s_getAttributeArgumentListNames = list => list.Arguments.Select( argument => argument.NameColon != null ? argument.NameColon.Name.Identifier.ValueText : argument.NameEquals?.Name.Identifier.ValueText); internal static SignatureHelpState? GetSignatureHelpState(BaseArgumentListSyntax argumentList, int position) { return CommonSignatureHelpUtilities.GetSignatureHelpState( argumentList, position, s_getBaseArgumentListOpenToken, s_getBaseArgumentListCloseToken, s_getBaseArgumentListArgumentsWithSeparators, s_getBaseArgumentListNames); } internal static SignatureHelpState? GetSignatureHelpState(TypeArgumentListSyntax argumentList, int position) { return CommonSignatureHelpUtilities.GetSignatureHelpState( argumentList, position, s_getTypeArgumentListOpenToken, s_getTypeArgumentListCloseToken, s_getTypeArgumentListArgumentsWithSeparators, s_getTypeArgumentListNames); } internal static SignatureHelpState? GetSignatureHelpState(InitializerExpressionSyntax argumentList, int position) { return CommonSignatureHelpUtilities.GetSignatureHelpState( argumentList, position, s_getInitializerExpressionOpenToken, s_getInitializerExpressionCloseToken, s_getInitializerExpressionArgumentsWithSeparators, s_getInitializerExpressionNames); } internal static SignatureHelpState? GetSignatureHelpState(AttributeArgumentListSyntax argumentList, int position) { return CommonSignatureHelpUtilities.GetSignatureHelpState( argumentList, position, s_getAttributeArgumentListOpenToken, s_getAttributeArgumentListCloseToken, s_getAttributeArgumentListArgumentsWithSeparators, s_getAttributeArgumentListNames); } internal static TextSpan GetSignatureHelpSpan(BaseArgumentListSyntax argumentList) => CommonSignatureHelpUtilities.GetSignatureHelpSpan(argumentList, s_getBaseArgumentListCloseToken); internal static TextSpan GetSignatureHelpSpan(TypeArgumentListSyntax argumentList) => CommonSignatureHelpUtilities.GetSignatureHelpSpan(argumentList, s_getTypeArgumentListCloseToken); internal static TextSpan GetSignatureHelpSpan(InitializerExpressionSyntax initializer) => CommonSignatureHelpUtilities.GetSignatureHelpSpan(initializer, initializer.SpanStart, s_getInitializerExpressionCloseToken); internal static TextSpan GetSignatureHelpSpan(AttributeArgumentListSyntax argumentList) => CommonSignatureHelpUtilities.GetSignatureHelpSpan(argumentList, s_getAttributeArgumentListCloseToken); internal static bool IsTriggerParenOrComma<TSyntaxNode>(SyntaxToken token, Func<char, bool> isTriggerCharacter) where TSyntaxNode : SyntaxNode { // Don't dismiss if the user types ( to start a parenthesized expression or tuple // Note that the tuple initially parses as a parenthesized expression if (token.IsKind(SyntaxKind.OpenParenToken) && token.Parent.IsKind(SyntaxKind.ParenthesizedExpression, out ParenthesizedExpressionSyntax? parenExpr)) { var parenthesizedExpr = parenExpr.WalkUpParentheses(); if (parenthesizedExpr.Parent is ArgumentSyntax) { var parent = parenthesizedExpr.Parent; var grandParent = parent.Parent; if (grandParent is ArgumentListSyntax && grandParent.Parent is TSyntaxNode) { // Argument to TSyntaxNode's argument list return true; } else { // Argument to a tuple in TSyntaxNode's argument list return grandParent is TupleExpressionSyntax && parenthesizedExpr.GetAncestor<TSyntaxNode>() != null; } } else { // Not an argument return false; } } // Don't dismiss if the user types ',' to add a member to a tuple if (token.IsKind(SyntaxKind.CommaToken) && token.Parent is TupleExpressionSyntax && token.GetAncestor<TSyntaxNode>() != null) { return true; } return !token.IsKind(SyntaxKind.None) && token.ValueText.Length == 1 && isTriggerCharacter(token.ValueText[0]) && token.Parent is ArgumentListSyntax && token.Parent.Parent is TSyntaxNode; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { internal static class SignatureHelpUtilities { private static readonly Func<BaseArgumentListSyntax, SyntaxToken> s_getBaseArgumentListOpenToken = list => list.GetOpenToken(); private static readonly Func<TypeArgumentListSyntax, SyntaxToken> s_getTypeArgumentListOpenToken = list => list.LessThanToken; private static readonly Func<InitializerExpressionSyntax, SyntaxToken> s_getInitializerExpressionOpenToken = e => e.OpenBraceToken; private static readonly Func<AttributeArgumentListSyntax, SyntaxToken> s_getAttributeArgumentListOpenToken = list => list.OpenParenToken; private static readonly Func<BaseArgumentListSyntax, SyntaxToken> s_getBaseArgumentListCloseToken = list => list.GetCloseToken(); private static readonly Func<TypeArgumentListSyntax, SyntaxToken> s_getTypeArgumentListCloseToken = list => list.GreaterThanToken; private static readonly Func<InitializerExpressionSyntax, SyntaxToken> s_getInitializerExpressionCloseToken = e => e.CloseBraceToken; private static readonly Func<AttributeArgumentListSyntax, SyntaxToken> s_getAttributeArgumentListCloseToken = list => list.CloseParenToken; private static readonly Func<BaseArgumentListSyntax, IEnumerable<SyntaxNodeOrToken>> s_getBaseArgumentListArgumentsWithSeparators = list => list.Arguments.GetWithSeparators(); private static readonly Func<TypeArgumentListSyntax, IEnumerable<SyntaxNodeOrToken>> s_getTypeArgumentListArgumentsWithSeparators = list => list.Arguments.GetWithSeparators(); private static readonly Func<InitializerExpressionSyntax, IEnumerable<SyntaxNodeOrToken>> s_getInitializerExpressionArgumentsWithSeparators = e => e.Expressions.GetWithSeparators(); private static readonly Func<AttributeArgumentListSyntax, IEnumerable<SyntaxNodeOrToken>> s_getAttributeArgumentListArgumentsWithSeparators = list => list.Arguments.GetWithSeparators(); private static readonly Func<BaseArgumentListSyntax, IEnumerable<string?>> s_getBaseArgumentListNames = list => list.Arguments.Select(argument => argument.NameColon?.Name.Identifier.ValueText); private static readonly Func<TypeArgumentListSyntax, IEnumerable<string?>> s_getTypeArgumentListNames = list => list.Arguments.Select(a => (string?)null); private static readonly Func<InitializerExpressionSyntax, IEnumerable<string?>> s_getInitializerExpressionNames = e => e.Expressions.Select(a => (string?)null); private static readonly Func<AttributeArgumentListSyntax, IEnumerable<string?>> s_getAttributeArgumentListNames = list => list.Arguments.Select( argument => argument.NameColon != null ? argument.NameColon.Name.Identifier.ValueText : argument.NameEquals?.Name.Identifier.ValueText); internal static SignatureHelpState? GetSignatureHelpState(BaseArgumentListSyntax argumentList, int position) { return CommonSignatureHelpUtilities.GetSignatureHelpState( argumentList, position, s_getBaseArgumentListOpenToken, s_getBaseArgumentListCloseToken, s_getBaseArgumentListArgumentsWithSeparators, s_getBaseArgumentListNames); } internal static SignatureHelpState? GetSignatureHelpState(TypeArgumentListSyntax argumentList, int position) { return CommonSignatureHelpUtilities.GetSignatureHelpState( argumentList, position, s_getTypeArgumentListOpenToken, s_getTypeArgumentListCloseToken, s_getTypeArgumentListArgumentsWithSeparators, s_getTypeArgumentListNames); } internal static SignatureHelpState? GetSignatureHelpState(InitializerExpressionSyntax argumentList, int position) { return CommonSignatureHelpUtilities.GetSignatureHelpState( argumentList, position, s_getInitializerExpressionOpenToken, s_getInitializerExpressionCloseToken, s_getInitializerExpressionArgumentsWithSeparators, s_getInitializerExpressionNames); } internal static SignatureHelpState? GetSignatureHelpState(AttributeArgumentListSyntax argumentList, int position) { return CommonSignatureHelpUtilities.GetSignatureHelpState( argumentList, position, s_getAttributeArgumentListOpenToken, s_getAttributeArgumentListCloseToken, s_getAttributeArgumentListArgumentsWithSeparators, s_getAttributeArgumentListNames); } internal static TextSpan GetSignatureHelpSpan(BaseArgumentListSyntax argumentList) => CommonSignatureHelpUtilities.GetSignatureHelpSpan(argumentList, s_getBaseArgumentListCloseToken); internal static TextSpan GetSignatureHelpSpan(TypeArgumentListSyntax argumentList) => CommonSignatureHelpUtilities.GetSignatureHelpSpan(argumentList, s_getTypeArgumentListCloseToken); internal static TextSpan GetSignatureHelpSpan(InitializerExpressionSyntax initializer) => CommonSignatureHelpUtilities.GetSignatureHelpSpan(initializer, initializer.SpanStart, s_getInitializerExpressionCloseToken); internal static TextSpan GetSignatureHelpSpan(AttributeArgumentListSyntax argumentList) => CommonSignatureHelpUtilities.GetSignatureHelpSpan(argumentList, s_getAttributeArgumentListCloseToken); internal static bool IsTriggerParenOrComma<TSyntaxNode>(SyntaxToken token, Func<char, bool> isTriggerCharacter) where TSyntaxNode : SyntaxNode { // Don't dismiss if the user types ( to start a parenthesized expression or tuple // Note that the tuple initially parses as a parenthesized expression if (token.IsKind(SyntaxKind.OpenParenToken) && token.Parent.IsKind(SyntaxKind.ParenthesizedExpression, out ParenthesizedExpressionSyntax? parenExpr)) { var parenthesizedExpr = parenExpr.WalkUpParentheses(); if (parenthesizedExpr.Parent is ArgumentSyntax) { var parent = parenthesizedExpr.Parent; var grandParent = parent.Parent; if (grandParent is ArgumentListSyntax && grandParent.Parent is TSyntaxNode) { // Argument to TSyntaxNode's argument list return true; } else { // Argument to a tuple in TSyntaxNode's argument list return grandParent is TupleExpressionSyntax && parenthesizedExpr.GetAncestor<TSyntaxNode>() != null; } } else { // Not an argument return false; } } // Don't dismiss if the user types ',' to add a member to a tuple if (token.IsKind(SyntaxKind.CommaToken) && token.Parent is TupleExpressionSyntax && token.GetAncestor<TSyntaxNode>() != null) { return true; } return !token.IsKind(SyntaxKind.None) && token.ValueText.Length == 1 && isTriggerCharacter(token.ValueText[0]) && token.Parent is ArgumentListSyntax && token.Parent.Parent is TSyntaxNode; } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/ExpressionEvaluator/Core/Test/FunctionResolver/Request.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; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests { internal struct Address { internal readonly Module Module; internal readonly int Token; internal readonly int Version; internal readonly int ILOffset; internal Address(Module module, int token, int version, int ilOffset) { Module = module; Token = token; Version = version; ILOffset = ilOffset; } } internal sealed class Request { private readonly List<Address> _resolvedAddresses; internal Request(string moduleName, RequestSignature signature, Guid languageId = default(Guid)) { ModuleName = moduleName; Signature = signature; LanguageId = languageId; _resolvedAddresses = new List<Address>(); } internal readonly string ModuleName; internal readonly RequestSignature Signature; internal readonly Guid LanguageId; internal void OnFunctionResolved(Module module, int token, int version, int ilOffset) { _resolvedAddresses.Add(new Address(module, token, version, ilOffset)); } internal ImmutableArray<Address> GetResolvedAddresses() { return ImmutableArray.CreateRange(_resolvedAddresses); } } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests { internal struct Address { internal readonly Module Module; internal readonly int Token; internal readonly int Version; internal readonly int ILOffset; internal Address(Module module, int token, int version, int ilOffset) { Module = module; Token = token; Version = version; ILOffset = ilOffset; } } internal sealed class Request { private readonly List<Address> _resolvedAddresses; internal Request(string moduleName, RequestSignature signature, Guid languageId = default(Guid)) { ModuleName = moduleName; Signature = signature; LanguageId = languageId; _resolvedAddresses = new List<Address>(); } internal readonly string ModuleName; internal readonly RequestSignature Signature; internal readonly Guid LanguageId; internal void OnFunctionResolved(Module module, int token, int version, int ilOffset) { _resolvedAddresses.Add(new Address(module, token, version, ilOffset)); } internal ImmutableArray<Address> GetResolvedAddresses() { return ImmutableArray.CreateRange(_resolvedAddresses); } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Analyzers/Core/Analyzers/AbstractParenthesesDiagnosticAnalyzer.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.CodeStyle; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Precedence; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses { internal abstract class AbstractParenthesesDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { protected AbstractParenthesesDiagnosticAnalyzer( string descriptorId, EnforceOnBuild enforceOnBuild, LocalizableString title, LocalizableString message, bool isUnnecessary = false) : base(descriptorId, enforceOnBuild, options: ImmutableHashSet.Create<IPerLanguageOption>(CodeStyleOptions2.ArithmeticBinaryParentheses, CodeStyleOptions2.RelationalBinaryParentheses, CodeStyleOptions2.OtherBinaryParentheses, CodeStyleOptions2.OtherParentheses), title, message, isUnnecessary: isUnnecessary) { } protected static PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> GetLanguageOption(PrecedenceKind precedenceKind) { switch (precedenceKind) { case PrecedenceKind.Arithmetic: case PrecedenceKind.Shift: case PrecedenceKind.Bitwise: return CodeStyleOptions2.ArithmeticBinaryParentheses; case PrecedenceKind.Relational: case PrecedenceKind.Equality: return CodeStyleOptions2.RelationalBinaryParentheses; case PrecedenceKind.Logical: case PrecedenceKind.Coalesce: return CodeStyleOptions2.OtherBinaryParentheses; case PrecedenceKind.Other: return CodeStyleOptions2.OtherParentheses; } throw ExceptionUtilities.UnexpectedValue(precedenceKind); } } }
// Licensed to the .NET Foundation under one or more 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.CodeStyle; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Precedence; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses { internal abstract class AbstractParenthesesDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { protected AbstractParenthesesDiagnosticAnalyzer( string descriptorId, EnforceOnBuild enforceOnBuild, LocalizableString title, LocalizableString message, bool isUnnecessary = false) : base(descriptorId, enforceOnBuild, options: ImmutableHashSet.Create<IPerLanguageOption>(CodeStyleOptions2.ArithmeticBinaryParentheses, CodeStyleOptions2.RelationalBinaryParentheses, CodeStyleOptions2.OtherBinaryParentheses, CodeStyleOptions2.OtherParentheses), title, message, isUnnecessary: isUnnecessary) { } protected static PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> GetLanguageOption(PrecedenceKind precedenceKind) { switch (precedenceKind) { case PrecedenceKind.Arithmetic: case PrecedenceKind.Shift: case PrecedenceKind.Bitwise: return CodeStyleOptions2.ArithmeticBinaryParentheses; case PrecedenceKind.Relational: case PrecedenceKind.Equality: return CodeStyleOptions2.RelationalBinaryParentheses; case PrecedenceKind.Logical: case PrecedenceKind.Coalesce: return CodeStyleOptions2.OtherBinaryParentheses; case PrecedenceKind.Other: return CodeStyleOptions2.OtherParentheses; } throw ExceptionUtilities.UnexpectedValue(precedenceKind); } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/SolutionCrawler/ISolutionCrawlerService.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 Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.SolutionCrawler { /// <summary> /// Provide a way to control solution crawler. /// </summary> internal interface ISolutionCrawlerService : IWorkspaceService { /// <summary> /// Ask solution crawler to re-analyze given <see cref="ProjectId"/>s or/and <see cref="DocumentId"/>s /// in given <see cref="Workspace"/> with given <see cref="IIncrementalAnalyzer"/>. /// </summary> void Reanalyze(Workspace workspace, IIncrementalAnalyzer analyzer, IEnumerable<ProjectId>? projectIds = null, IEnumerable<DocumentId>? documentIds = null, bool highPriority = false); /// <summary> /// Get <see cref="ISolutionCrawlerProgressReporter"/> for the given <see cref="Workspace"/> /// </summary> ISolutionCrawlerProgressReporter GetProgressReporter(Workspace workspace); } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.SolutionCrawler { /// <summary> /// Provide a way to control solution crawler. /// </summary> internal interface ISolutionCrawlerService : IWorkspaceService { /// <summary> /// Ask solution crawler to re-analyze given <see cref="ProjectId"/>s or/and <see cref="DocumentId"/>s /// in given <see cref="Workspace"/> with given <see cref="IIncrementalAnalyzer"/>. /// </summary> void Reanalyze(Workspace workspace, IIncrementalAnalyzer analyzer, IEnumerable<ProjectId>? projectIds = null, IEnumerable<DocumentId>? documentIds = null, bool highPriority = false); /// <summary> /// Get <see cref="ISolutionCrawlerProgressReporter"/> for the given <see cref="Workspace"/> /// </summary> ISolutionCrawlerProgressReporter GetProgressReporter(Workspace workspace); } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/ExtractMethod/CSharpSelectionValidator.Validator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal partial class CSharpSelectionValidator { public static bool Check(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) => node switch { ExpressionSyntax expression => CheckExpression(semanticModel, expression, cancellationToken), BlockSyntax block => CheckBlock(block), StatementSyntax statement => CheckStatement(statement), GlobalStatementSyntax _ => CheckGlobalStatement(), _ => false, }; private static bool CheckGlobalStatement() => true; private static bool CheckBlock(BlockSyntax block) { // TODO(cyrusn): Is it intentional that fixed statement is not in this list? return block.Parent is BlockSyntax || block.Parent is DoStatementSyntax || block.Parent is ElseClauseSyntax || block.Parent is CommonForEachStatementSyntax || block.Parent is ForStatementSyntax || block.Parent is IfStatementSyntax || block.Parent is LockStatementSyntax || block.Parent is UsingStatementSyntax || block.Parent is WhileStatementSyntax; } private static bool CheckExpression(SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // TODO(cyrusn): This is probably unnecessary. What we should be doing is binding // the type of the expression and seeing if it contains an anonymous type. if (expression is AnonymousObjectCreationExpressionSyntax) { return false; } return expression.CanReplaceWithRValue(semanticModel, cancellationToken); } private static bool CheckStatement(StatementSyntax statement) => statement is CheckedStatementSyntax || statement is DoStatementSyntax || statement is EmptyStatementSyntax || statement is ExpressionStatementSyntax || statement is FixedStatementSyntax || statement is CommonForEachStatementSyntax || statement is ForStatementSyntax || statement is IfStatementSyntax || statement is LocalDeclarationStatementSyntax || statement is LockStatementSyntax || statement is ReturnStatementSyntax || statement is SwitchStatementSyntax || statement is ThrowStatementSyntax || statement is TryStatementSyntax || statement is UnsafeStatementSyntax || statement is UsingStatementSyntax || statement is WhileStatementSyntax; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal partial class CSharpSelectionValidator { public static bool Check(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) => node switch { ExpressionSyntax expression => CheckExpression(semanticModel, expression, cancellationToken), BlockSyntax block => CheckBlock(block), StatementSyntax statement => CheckStatement(statement), GlobalStatementSyntax _ => CheckGlobalStatement(), _ => false, }; private static bool CheckGlobalStatement() => true; private static bool CheckBlock(BlockSyntax block) { // TODO(cyrusn): Is it intentional that fixed statement is not in this list? return block.Parent is BlockSyntax || block.Parent is DoStatementSyntax || block.Parent is ElseClauseSyntax || block.Parent is CommonForEachStatementSyntax || block.Parent is ForStatementSyntax || block.Parent is IfStatementSyntax || block.Parent is LockStatementSyntax || block.Parent is UsingStatementSyntax || block.Parent is WhileStatementSyntax; } private static bool CheckExpression(SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // TODO(cyrusn): This is probably unnecessary. What we should be doing is binding // the type of the expression and seeing if it contains an anonymous type. if (expression is AnonymousObjectCreationExpressionSyntax) { return false; } return expression.CanReplaceWithRValue(semanticModel, cancellationToken); } private static bool CheckStatement(StatementSyntax statement) => statement is CheckedStatementSyntax || statement is DoStatementSyntax || statement is EmptyStatementSyntax || statement is ExpressionStatementSyntax || statement is FixedStatementSyntax || statement is CommonForEachStatementSyntax || statement is ForStatementSyntax || statement is IfStatementSyntax || statement is LocalDeclarationStatementSyntax || statement is LockStatementSyntax || statement is ReturnStatementSyntax || statement is SwitchStatementSyntax || statement is ThrowStatementSyntax || statement is TryStatementSyntax || statement is UnsafeStatementSyntax || statement is UsingStatementSyntax || statement is WhileStatementSyntax; } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/Helpers.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.Completion; using Microsoft.VisualStudio.Text; using EditorAsyncCompletion = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using EditorAsyncCompletionData = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem; using RoslynTrigger = Microsoft.CodeAnalysis.Completion.CompletionTrigger; using VSCompletionItem = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data.CompletionItem; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion { internal static class Helpers { /// <summary> /// Attempts to convert VS Completion trigger into Roslyn completion trigger /// </summary> /// <param name="trigger">VS completion trigger</param> /// <param name="triggerLocation">Character. /// VS provides Backspace and Delete characters inside the trigger while Roslyn needs the char deleted by the trigger. /// Therefore, we provide this character separately and use it for Delete and Backspace cases only. /// We retrieve this character from triggerLocation. /// </param> /// <returns>Roslyn completion trigger</returns> internal static RoslynTrigger GetRoslynTrigger(EditorAsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation) { var completionTriggerKind = GetRoslynTriggerKind(trigger); if (completionTriggerKind == CompletionTriggerKind.Deletion) { var snapshotBeforeEdit = trigger.ViewSnapshotBeforeTrigger; char characterRemoved; if (triggerLocation.Position >= 0 && triggerLocation.Position < snapshotBeforeEdit.Length) { // If multiple characters were removed (selection), this finds the first character from the left. characterRemoved = snapshotBeforeEdit[triggerLocation.Position]; } else { characterRemoved = (char)0; } return RoslynTrigger.CreateDeletionTrigger(characterRemoved); } else { return new RoslynTrigger(completionTriggerKind, trigger.Character); } } internal static CompletionTriggerKind GetRoslynTriggerKind(EditorAsyncCompletionData.CompletionTrigger trigger) { switch (trigger.Reason) { case EditorAsyncCompletionData.CompletionTriggerReason.InvokeAndCommitIfUnique: return CompletionTriggerKind.InvokeAndCommitIfUnique; case EditorAsyncCompletionData.CompletionTriggerReason.Insertion: return CompletionTriggerKind.Insertion; case EditorAsyncCompletionData.CompletionTriggerReason.Deletion: case EditorAsyncCompletionData.CompletionTriggerReason.Backspace: return CompletionTriggerKind.Deletion; case EditorAsyncCompletionData.CompletionTriggerReason.SnippetsMode: return CompletionTriggerKind.Snippets; default: return CompletionTriggerKind.Invoke; } } internal static CompletionFilterReason GetFilterReason(EditorAsyncCompletionData.CompletionTrigger trigger) { switch (trigger.Reason) { case EditorAsyncCompletionData.CompletionTriggerReason.Insertion: return CompletionFilterReason.Insertion; case EditorAsyncCompletionData.CompletionTriggerReason.Deletion: case EditorAsyncCompletionData.CompletionTriggerReason.Backspace: return CompletionFilterReason.Deletion; default: return CompletionFilterReason.Other; } } internal static bool IsFilterCharacter(RoslynCompletionItem item, char ch, string textTypedSoFar) { // Exclude standard commit character upfront because TextTypedSoFarMatchesItem can miss them on non-Windows platforms. if (IsStandardCommitCharacter(ch)) { return false; } // First see if the item has any specific filter rules it wants followed. foreach (var rule in item.Rules.FilterCharacterRules) { switch (rule.Kind) { case CharacterSetModificationKind.Add: if (rule.Characters.Contains(ch)) { return true; } continue; case CharacterSetModificationKind.Remove: if (rule.Characters.Contains(ch)) { return false; } continue; case CharacterSetModificationKind.Replace: return rule.Characters.Contains(ch); } } // general rule: if the filtering text exactly matches the start of the item then it must be a filter character if (TextTypedSoFarMatchesItem(item, textTypedSoFar)) { return true; } return false; } internal static bool TextTypedSoFarMatchesItem(RoslynCompletionItem item, string textTypedSoFar) { if (textTypedSoFar.Length > 0) { // Note that StartsWith ignores \0 at the end of textTypedSoFar on VS Mac and Mono. return item.DisplayText.StartsWith(textTypedSoFar, StringComparison.CurrentCultureIgnoreCase) || item.FilterText.StartsWith(textTypedSoFar, StringComparison.CurrentCultureIgnoreCase); } return false; } // Tab, Enter and Null (call invoke commit) are always commit characters. internal static bool IsStandardCommitCharacter(char c) => c == '\t' || c == '\n' || c == '\0'; internal static bool TryGetInitialTriggerLocation(EditorAsyncCompletion.IAsyncCompletionSession session, out SnapshotPoint initialTriggerLocation) => session.Properties.TryGetProperty(CompletionSource.TriggerLocation, out initialTriggerLocation); // This is a temporarily method to support preference of IntelliCode items comparing to non-IntelliCode items. // We expect that Editor will introduce this support and we will get rid of relying on the "★" then. internal static bool IsPreferredItem(this VSCompletionItem completionItem) => completionItem.DisplayText.StartsWith("★"); } }
// Licensed to the .NET Foundation under one or more 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.Completion; using Microsoft.VisualStudio.Text; using EditorAsyncCompletion = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using EditorAsyncCompletionData = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem; using RoslynTrigger = Microsoft.CodeAnalysis.Completion.CompletionTrigger; using VSCompletionItem = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data.CompletionItem; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion { internal static class Helpers { /// <summary> /// Attempts to convert VS Completion trigger into Roslyn completion trigger /// </summary> /// <param name="trigger">VS completion trigger</param> /// <param name="triggerLocation">Character. /// VS provides Backspace and Delete characters inside the trigger while Roslyn needs the char deleted by the trigger. /// Therefore, we provide this character separately and use it for Delete and Backspace cases only. /// We retrieve this character from triggerLocation. /// </param> /// <returns>Roslyn completion trigger</returns> internal static RoslynTrigger GetRoslynTrigger(EditorAsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation) { var completionTriggerKind = GetRoslynTriggerKind(trigger); if (completionTriggerKind == CompletionTriggerKind.Deletion) { var snapshotBeforeEdit = trigger.ViewSnapshotBeforeTrigger; char characterRemoved; if (triggerLocation.Position >= 0 && triggerLocation.Position < snapshotBeforeEdit.Length) { // If multiple characters were removed (selection), this finds the first character from the left. characterRemoved = snapshotBeforeEdit[triggerLocation.Position]; } else { characterRemoved = (char)0; } return RoslynTrigger.CreateDeletionTrigger(characterRemoved); } else { return new RoslynTrigger(completionTriggerKind, trigger.Character); } } internal static CompletionTriggerKind GetRoslynTriggerKind(EditorAsyncCompletionData.CompletionTrigger trigger) { switch (trigger.Reason) { case EditorAsyncCompletionData.CompletionTriggerReason.InvokeAndCommitIfUnique: return CompletionTriggerKind.InvokeAndCommitIfUnique; case EditorAsyncCompletionData.CompletionTriggerReason.Insertion: return CompletionTriggerKind.Insertion; case EditorAsyncCompletionData.CompletionTriggerReason.Deletion: case EditorAsyncCompletionData.CompletionTriggerReason.Backspace: return CompletionTriggerKind.Deletion; case EditorAsyncCompletionData.CompletionTriggerReason.SnippetsMode: return CompletionTriggerKind.Snippets; default: return CompletionTriggerKind.Invoke; } } internal static CompletionFilterReason GetFilterReason(EditorAsyncCompletionData.CompletionTrigger trigger) { switch (trigger.Reason) { case EditorAsyncCompletionData.CompletionTriggerReason.Insertion: return CompletionFilterReason.Insertion; case EditorAsyncCompletionData.CompletionTriggerReason.Deletion: case EditorAsyncCompletionData.CompletionTriggerReason.Backspace: return CompletionFilterReason.Deletion; default: return CompletionFilterReason.Other; } } internal static bool IsFilterCharacter(RoslynCompletionItem item, char ch, string textTypedSoFar) { // Exclude standard commit character upfront because TextTypedSoFarMatchesItem can miss them on non-Windows platforms. if (IsStandardCommitCharacter(ch)) { return false; } // First see if the item has any specific filter rules it wants followed. foreach (var rule in item.Rules.FilterCharacterRules) { switch (rule.Kind) { case CharacterSetModificationKind.Add: if (rule.Characters.Contains(ch)) { return true; } continue; case CharacterSetModificationKind.Remove: if (rule.Characters.Contains(ch)) { return false; } continue; case CharacterSetModificationKind.Replace: return rule.Characters.Contains(ch); } } // general rule: if the filtering text exactly matches the start of the item then it must be a filter character if (TextTypedSoFarMatchesItem(item, textTypedSoFar)) { return true; } return false; } internal static bool TextTypedSoFarMatchesItem(RoslynCompletionItem item, string textTypedSoFar) { if (textTypedSoFar.Length > 0) { // Note that StartsWith ignores \0 at the end of textTypedSoFar on VS Mac and Mono. return item.DisplayText.StartsWith(textTypedSoFar, StringComparison.CurrentCultureIgnoreCase) || item.FilterText.StartsWith(textTypedSoFar, StringComparison.CurrentCultureIgnoreCase); } return false; } // Tab, Enter and Null (call invoke commit) are always commit characters. internal static bool IsStandardCommitCharacter(char c) => c == '\t' || c == '\n' || c == '\0'; internal static bool TryGetInitialTriggerLocation(EditorAsyncCompletion.IAsyncCompletionSession session, out SnapshotPoint initialTriggerLocation) => session.Properties.TryGetProperty(CompletionSource.TriggerLocation, out initialTriggerLocation); // This is a temporarily method to support preference of IntelliCode items comparing to non-IntelliCode items. // We expect that Editor will introduce this support and we will get rid of relying on the "★" then. internal static bool IsPreferredItem(this VSCompletionItem completionItem) => completionItem.DisplayText.StartsWith("★"); } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest2/Recommendations/UnsafeKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class UnsafeKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCompilationUnit() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExtern() { await VerifyKeywordAsync( @"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync( @"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync( @"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync( @"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeDeclaration() { await VerifyKeywordAsync( @"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync( @"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ global using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync( @"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute() { await VerifyKeywordAsync( @"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } // This will be fixed once we have accessibility for members [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync( @"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAbstract() { await VerifyKeywordAsync( @"abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal() { await VerifyKeywordAsync( @"internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterUnsafe() => await VerifyAbsenceAsync(@"unsafe $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticUnsafe() => await VerifyAbsenceAsync(@"static unsafe $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterUnsafeStatic() => await VerifyAbsenceAsync(@"unsafe static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate() { await VerifyKeywordAsync( @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProtected() { await VerifyKeywordAsync( @"protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSealed() { await VerifyKeywordAsync( @"sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatic() { await VerifyKeywordAsync( @"static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticInUsingDirective() { await VerifyAbsenceAsync( @"using static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticInGlobalUsingDirective() { await VerifyAbsenceAsync( @"global using static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass() => await VerifyAbsenceAsync(@"class $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAbstract() { await VerifyKeywordAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedVirtual() { await VerifyKeywordAsync( @"class C { virtual $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedOverride() { await VerifyKeywordAsync( @"class C { override $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedSealed() { await VerifyKeywordAsync( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBeforeStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$ return true;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatement() { await VerifyKeywordAsync(AddInsideMethod( @"return true; $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterBlock() { await VerifyKeywordAsync(AddInsideMethod( @"if (true) { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideSwitchBlock() { await VerifyKeywordAsync(AddInsideMethod( @"switch (E) { case 0: $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterUnsafe_InMethod() { await VerifyAbsenceAsync(AddInsideMethod( @"unsafe $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInterfaceModifiers() { await VerifyKeywordAsync( @"public $$ interface IBinaryDocumentMemoryBlock {"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class UnsafeKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCompilationUnit() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExtern() { await VerifyKeywordAsync( @"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync( @"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync( @"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync( @"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeDeclaration() { await VerifyKeywordAsync( @"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync( @"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ global using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync( @"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute() { await VerifyKeywordAsync( @"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } // This will be fixed once we have accessibility for members [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync( @"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAbstract() { await VerifyKeywordAsync( @"abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal() { await VerifyKeywordAsync( @"internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterUnsafe() => await VerifyAbsenceAsync(@"unsafe $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticUnsafe() => await VerifyAbsenceAsync(@"static unsafe $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterUnsafeStatic() => await VerifyAbsenceAsync(@"unsafe static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate() { await VerifyKeywordAsync( @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProtected() { await VerifyKeywordAsync( @"protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSealed() { await VerifyKeywordAsync( @"sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatic() { await VerifyKeywordAsync( @"static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticInUsingDirective() { await VerifyAbsenceAsync( @"using static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticInGlobalUsingDirective() { await VerifyAbsenceAsync( @"global using static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass() => await VerifyAbsenceAsync(@"class $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAbstract() { await VerifyKeywordAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedVirtual() { await VerifyKeywordAsync( @"class C { virtual $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedOverride() { await VerifyKeywordAsync( @"class C { override $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedSealed() { await VerifyKeywordAsync( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBeforeStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$ return true;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatement() { await VerifyKeywordAsync(AddInsideMethod( @"return true; $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterBlock() { await VerifyKeywordAsync(AddInsideMethod( @"if (true) { } $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideSwitchBlock() { await VerifyKeywordAsync(AddInsideMethod( @"switch (E) { case 0: $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterUnsafe_InMethod() { await VerifyAbsenceAsync(AddInsideMethod( @"unsafe $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInterfaceModifiers() { await VerifyKeywordAsync( @"public $$ interface IBinaryDocumentMemoryBlock {"); } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core.Wpf/Peek/PeekableItemFactory.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.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.Editor.Peek; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Language.Intellisense; namespace Microsoft.CodeAnalysis.Editor.Implementation.Peek { [Export(typeof(IPeekableItemFactory))] internal class PeekableItemFactory : IPeekableItemFactory { private readonly IMetadataAsSourceFileService _metadataAsSourceFileService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PeekableItemFactory(IMetadataAsSourceFileService metadataAsSourceFileService) => _metadataAsSourceFileService = metadataAsSourceFileService; public async Task<IEnumerable<IPeekableItem>> GetPeekableItemsAsync( ISymbol symbol, Project project, IPeekResultFactory peekResultFactory, CancellationToken cancellationToken) { if (symbol == null) { throw new ArgumentNullException(nameof(symbol)); } if (project == null) { throw new ArgumentNullException(nameof(project)); } if (peekResultFactory == null) { throw new ArgumentNullException(nameof(peekResultFactory)); } var results = new List<IPeekableItem>(); var solution = project.Solution; var sourceDefinition = await SymbolFinder.FindSourceDefinitionAsync(symbol, solution, cancellationToken).ConfigureAwait(false); // And if our definition actually is from source, then let's re-figure out what project it came from if (sourceDefinition != null) { var originatingProject = solution.GetProject(sourceDefinition.ContainingAssembly, cancellationToken); project = originatingProject ?? project; } var symbolNavigationService = solution.Workspace.Services.GetService<ISymbolNavigationService>(); var definitionItem = symbol.ToNonClassifiedDefinitionItem(solution, includeHiddenLocations: true); if (symbolNavigationService.WouldNavigateToSymbol( definitionItem, solution, cancellationToken, out var filePath, out var lineNumber, out var charOffset)) { var position = new LinePosition(lineNumber, charOffset); results.Add(new ExternalFilePeekableItem(new FileLinePositionSpan(filePath, position, position), PredefinedPeekRelationships.Definitions, peekResultFactory)); } else { var symbolKey = SymbolKey.Create(symbol, cancellationToken); var firstLocation = symbol.Locations.FirstOrDefault(); if (firstLocation != null) { if (firstLocation.IsInSource || _metadataAsSourceFileService.IsNavigableMetadataSymbol(symbol)) { results.Add(new DefinitionPeekableItem(solution.Workspace, project.Id, symbolKey, peekResultFactory, _metadataAsSourceFileService)); } } } return results; } } }
// Licensed to the .NET Foundation under one or more 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.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.Editor.Peek; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Language.Intellisense; namespace Microsoft.CodeAnalysis.Editor.Implementation.Peek { [Export(typeof(IPeekableItemFactory))] internal class PeekableItemFactory : IPeekableItemFactory { private readonly IMetadataAsSourceFileService _metadataAsSourceFileService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PeekableItemFactory(IMetadataAsSourceFileService metadataAsSourceFileService) => _metadataAsSourceFileService = metadataAsSourceFileService; public async Task<IEnumerable<IPeekableItem>> GetPeekableItemsAsync( ISymbol symbol, Project project, IPeekResultFactory peekResultFactory, CancellationToken cancellationToken) { if (symbol == null) { throw new ArgumentNullException(nameof(symbol)); } if (project == null) { throw new ArgumentNullException(nameof(project)); } if (peekResultFactory == null) { throw new ArgumentNullException(nameof(peekResultFactory)); } var results = new List<IPeekableItem>(); var solution = project.Solution; var sourceDefinition = await SymbolFinder.FindSourceDefinitionAsync(symbol, solution, cancellationToken).ConfigureAwait(false); // And if our definition actually is from source, then let's re-figure out what project it came from if (sourceDefinition != null) { var originatingProject = solution.GetProject(sourceDefinition.ContainingAssembly, cancellationToken); project = originatingProject ?? project; } var symbolNavigationService = solution.Workspace.Services.GetService<ISymbolNavigationService>(); var definitionItem = symbol.ToNonClassifiedDefinitionItem(solution, includeHiddenLocations: true); if (symbolNavigationService.WouldNavigateToSymbol( definitionItem, solution, cancellationToken, out var filePath, out var lineNumber, out var charOffset)) { var position = new LinePosition(lineNumber, charOffset); results.Add(new ExternalFilePeekableItem(new FileLinePositionSpan(filePath, position, position), PredefinedPeekRelationships.Definitions, peekResultFactory)); } else { var symbolKey = SymbolKey.Create(symbol, cancellationToken); var firstLocation = symbol.Locations.FirstOrDefault(); if (firstLocation != null) { if (firstLocation.IsInSource || _metadataAsSourceFileService.IsNavigableMetadataSymbol(symbol)) { results.Add(new DefinitionPeekableItem(solution.Workspace, project.Id, symbolKey, peekResultFactory, _metadataAsSourceFileService)); } } } return results; } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpGenerateTypeDialog.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; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpGenerateTypeDialog : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; private GenerateTypeDialog_OutOfProc GenerateTypeDialog => VisualStudio.GenerateTypeDialog; public CSharpGenerateTypeDialog(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpGenerateTypeDialog)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public void OpenAndCloseDialog() { SetUpEditor(@"class C { void Method() { $$A a; } } "); VisualStudio.Editor.Verify.CodeAction("Generate new type...", applyFix: true, blockUntilComplete: false); GenerateTypeDialog.VerifyOpen(); GenerateTypeDialog.ClickCancel(); GenerateTypeDialog.VerifyClosed(); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public void CSharpToBasic() { var vbProj = new ProjectUtils.Project("VBProj"); VisualStudio.SolutionExplorer.AddProject(vbProj, WellKnownProjectTemplates.ClassLibrary, LanguageNames.VisualBasic); var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.OpenFile(project, "Class1.cs"); SetUpEditor(@"class C { void Method() { $$A a; } } "); VisualStudio.Editor.Verify.CodeAction("Generate new type...", applyFix: true, blockUntilComplete: false); GenerateTypeDialog.VerifyOpen(); GenerateTypeDialog.SetAccessibility("public"); GenerateTypeDialog.SetKind("interface"); GenerateTypeDialog.SetTargetProject("VBProj"); GenerateTypeDialog.SetTargetFileToNewName("GenerateTypeTest"); GenerateTypeDialog.ClickOK(); GenerateTypeDialog.VerifyClosed(); VisualStudio.SolutionExplorer.OpenFile(vbProj, "GenerateTypeTest.vb"); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@"Public Interface A End Interface ", actualText); VisualStudio.SolutionExplorer.OpenFile(project, "Class1.cs"); actualText = VisualStudio.Editor.GetText(); Assert.Contains(@"using VBProj; class C { void Method() { A a; } } ", 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.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 CSharpGenerateTypeDialog : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; private GenerateTypeDialog_OutOfProc GenerateTypeDialog => VisualStudio.GenerateTypeDialog; public CSharpGenerateTypeDialog(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpGenerateTypeDialog)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public void OpenAndCloseDialog() { SetUpEditor(@"class C { void Method() { $$A a; } } "); VisualStudio.Editor.Verify.CodeAction("Generate new type...", applyFix: true, blockUntilComplete: false); GenerateTypeDialog.VerifyOpen(); GenerateTypeDialog.ClickCancel(); GenerateTypeDialog.VerifyClosed(); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)] public void CSharpToBasic() { var vbProj = new ProjectUtils.Project("VBProj"); VisualStudio.SolutionExplorer.AddProject(vbProj, WellKnownProjectTemplates.ClassLibrary, LanguageNames.VisualBasic); var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.OpenFile(project, "Class1.cs"); SetUpEditor(@"class C { void Method() { $$A a; } } "); VisualStudio.Editor.Verify.CodeAction("Generate new type...", applyFix: true, blockUntilComplete: false); GenerateTypeDialog.VerifyOpen(); GenerateTypeDialog.SetAccessibility("public"); GenerateTypeDialog.SetKind("interface"); GenerateTypeDialog.SetTargetProject("VBProj"); GenerateTypeDialog.SetTargetFileToNewName("GenerateTypeTest"); GenerateTypeDialog.ClickOK(); GenerateTypeDialog.VerifyClosed(); VisualStudio.SolutionExplorer.OpenFile(vbProj, "GenerateTypeTest.vb"); var actualText = VisualStudio.Editor.GetText(); Assert.Contains(@"Public Interface A End Interface ", actualText); VisualStudio.SolutionExplorer.OpenFile(project, "Class1.cs"); actualText = VisualStudio.Editor.GetText(); Assert.Contains(@"using VBProj; class C { void Method() { A a; } } ", actualText); } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Test/Symbol/Compilation/CompilationAPITests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Reflection.PortableExecutable; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using VB = Microsoft.CodeAnalysis.VisualBasic; using KeyValuePairUtil = Roslyn.Utilities.KeyValuePairUtil; using System.Security.Cryptography; using static Roslyn.Test.Utilities.TestHelpers; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class CompilationAPITests : CSharpTestBase { private CSharpCompilationOptions WithDiagnosticOptions( SyntaxTree tree, params (string, ReportDiagnostic)[] options) => TestOptions.DebugDll.WithSyntaxTreeOptionsProvider(new TestSyntaxTreeOptionsProvider(tree, options)); [Fact] public void TreeDiagnosticOptionsDoNotAffectTreeDiagnostics() { #pragma warning disable CS0618 // This test is intentionally calling the obsolete method to assert the diagnosticOptions input is now ignored var tree = SyntaxFactory.ParseSyntaxTree("class C { long _f = 0l;}", options: null, path: "", encoding: null, diagnosticOptions: CreateImmutableDictionary(("CS0078", ReportDiagnostic.Suppress)), cancellationToken: default); tree.GetDiagnostics().Verify( // (1,22): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // class C { long _f = 0l;} Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(1, 22)); #pragma warning restore CS0618 } [Fact] public void PerTreeVsGlobalSuppress() { var tree = SyntaxFactory.ParseSyntaxTree("class C { long _f = 0l;}"); var options = TestOptions.DebugDll .WithGeneralDiagnosticOption(ReportDiagnostic.Suppress); var comp = CreateCompilation(tree, options: options); comp.VerifyDiagnostics(); options = options.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider((tree, new[] { ("CS0078", ReportDiagnostic.Warn) }))); comp = CreateCompilation(tree, options: options); // Syntax tree diagnostic options override global settting comp.VerifyDiagnostics( // (1,22): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // class C { long _f = 0l;} Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(1, 22)); } [Fact] public void PerTreeDiagnosticOptionsParseWarnings() { var tree = SyntaxFactory.ParseSyntaxTree("class C { long _f = 0l;}"); var comp = CreateCompilation(tree); comp.VerifyDiagnostics( // (1,22): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // class C { long _f = 0l;} Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(1, 22), // (1,16): warning CS0414: The field 'C._f' is assigned but its value is never used // class C { long _f = 0l;} Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(1, 16)); var options = WithDiagnosticOptions(tree, ("CS0078", ReportDiagnostic.Suppress)); comp = CreateCompilation(tree, options: options); comp.VerifyDiagnostics( // (1,16): warning CS0414: The field 'C._f' is assigned but its value is never used // class C { long _f = 0l;} Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(1, 16)); } [Fact] public void PerTreeDiagnosticOptionsVsPragma() { var tree = SyntaxFactory.ParseSyntaxTree(@" class C { #pragma warning disable CS0078 long _f = 0l; #pragma warning restore CS0078 }"); tree.GetDiagnostics().Verify( // (4,12): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // long _f = 0l; Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(4, 12)); var comp = CreateCompilation(tree); comp.VerifyDiagnostics( // (4,6): warning CS0414: The field 'C._f' is assigned but its value is never used // long _f = 0l; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(4, 6)); var options = WithDiagnosticOptions(tree, ("CS0078", ReportDiagnostic.Error)); comp = CreateCompilation(tree, options: options); // Pragma should have precedence over per-tree options comp.VerifyDiagnostics( // (4,6): warning CS0414: The field 'C._f' is assigned but its value is never used // long _f = 0l; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(4, 6)); } [Fact] public void PerTreeDiagnosticOptionsVsSpecificOptions() { var tree = SyntaxFactory.ParseSyntaxTree("class C { long _f = 0l; }"); var options = WithDiagnosticOptions(tree, ("CS0078", ReportDiagnostic.Suppress)); var comp = CreateCompilation(tree, options: options); comp.VerifyDiagnostics( // (1,16): warning CS0414: The field 'C._f' is assigned but its value is never used // class C { long _f = 0l; } Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(1, 16) ); options = options.WithSpecificDiagnosticOptions( CreateImmutableDictionary(("CS0078", ReportDiagnostic.Error))); var comp2 = CreateCompilation(tree, options: options); // Specific diagnostic options have precedence over per-tree options comp2.VerifyDiagnostics( // (1,16): warning CS0414: The field 'C._f' is assigned but its value is never used // class C { long _f = 0l; } Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(1, 16), // (1,22): error CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // class C { long _f = 0l; } Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(1, 22).WithWarningAsError(true)); } [Fact] public void DifferentDiagnosticOptionsForTrees() { var tree = SyntaxFactory.ParseSyntaxTree(@" class C { long _f = 0l; }"); var newTree = SyntaxFactory.ParseSyntaxTree(@" class D { long _f = 0l; }"); var options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider( (tree, new[] { ("CS0078", ReportDiagnostic.Suppress) }), (newTree, new[] { ("CS0078", ReportDiagnostic.Error) }) ) ); var comp = CreateCompilation(new[] { tree, newTree }, options: options); comp.VerifyDiagnostics( // (1,23): error CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // class D { long _f = 0l; } Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(1, 23).WithWarningAsError(true), // (1,17): warning CS0414: The field 'D._f' is assigned but its value is never used // class D { long _f = 0l; } Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("D._f").WithLocation(1, 17), // (1,17): warning CS0414: The field 'C._f' is assigned but its value is never used // class C { long _f = 0l; } Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(1, 17) ); } [Fact] public void TreeOptionsComparerRespected() { var tree = SyntaxFactory.ParseSyntaxTree(@" class C { long _f = 0l; }"); // Default options have case insensitivity var options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider((tree, new[] { ("cs0078", ReportDiagnostic.Suppress) })) ); CreateCompilation(tree, options: options).VerifyDiagnostics( // (1,17): warning CS0414: The field 'C._f' is assigned but its value is never used // class C { long _f = 0l; } Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(1, 17) ); options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider( StringComparer.Ordinal, globalOption: default, (tree, new[] { ("cs0078", ReportDiagnostic.Suppress) })) ); CreateCompilation(tree, options: options).VerifyDiagnostics( // (1,23): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // class C { long _f = 0l; } Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(1, 23), // (1,17): warning CS0414: The field 'C._f' is assigned but its value is never used // class C { long _f = 0l; } Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(1, 17) ); } [Fact] public void WarningLevelRespectedForLexerWarnings() { var source = @"public class C { public long Field = 0l; }"; CreateCompilation(source).VerifyDiagnostics( // (1,39): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // public class C { public long Field = 0l; } Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(1, 39) ); CreateCompilation(source, options: TestOptions.ReleaseDll.WithWarningLevel(0)).VerifyDiagnostics( ); } [WorkItem(8360, "https://github.com/dotnet/roslyn/issues/8360")] [WorkItem(9153, "https://github.com/dotnet/roslyn/issues/9153")] [Fact] public void PublicSignWithRelativeKeyPath() { var options = TestOptions.DebugDll .WithPublicSign(true).WithCryptoKeyFile("test.snk"); var comp = CSharpCompilation.Create("test", options: options); comp.VerifyDiagnostics( // error CS7104: Option 'CryptoKeyFile' must be an absolute path. Diagnostic(ErrorCode.ERR_OptionMustBeAbsolutePath).WithArguments("CryptoKeyFile").WithLocation(1, 1), // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1) ); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void PublicSignWithEmptyKeyPath() { CreateCompilation("", options: TestOptions.ReleaseDll.WithPublicSign(true).WithCryptoKeyFile("")).VerifyDiagnostics( // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1)); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void PublicSignWithEmptyKeyPath2() { CreateCompilation("", options: TestOptions.ReleaseDll.WithPublicSign(true).WithCryptoKeyFile("\"\"")).VerifyDiagnostics( // error CS8106: Option 'CryptoKeyFile' must be an absolute path. Diagnostic(ErrorCode.ERR_OptionMustBeAbsolutePath).WithArguments("CryptoKeyFile").WithLocation(1, 1), // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1)); } [Fact] [WorkItem(233669, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=233669")] public void CompilationName() { // report an error, rather then silently ignoring the directory // (see cli partition II 22.30) CSharpCompilation.Create(@"C:/goo/Test.exe").VerifyEmitDiagnostics( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1), // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1), // error CS5001: Program does not contain a static 'Main' method suitable for an entry point Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1) ); CSharpCompilation.Create(@"C:\goo\Test.exe").GetDeclarationDiagnostics().Verify( // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); var compilationOptions = TestOptions.DebugDll.WithWarningLevel(0); CSharpCompilation.Create(@"\goo/Test.exe", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); CSharpCompilation.Create(@"C:Test.exe", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); CSharpCompilation.Create(@"Te\0st.exe", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); CSharpCompilation.Create(@" \t ", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name cannot start with whitespace. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name cannot start with whitespace.").WithLocation(1, 1) ); CSharpCompilation.Create(@"\uD800", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); CSharpCompilation.Create(@"", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name cannot be empty. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name cannot be empty.").WithLocation(1, 1) ); CSharpCompilation.Create(@" a", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name cannot start with whitespace. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name cannot start with whitespace.").WithLocation(1, 1) ); CSharpCompilation.Create(@"\u2000a", options: compilationOptions).VerifyEmitDiagnostics( // U+20700 is whitespace // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); CSharpCompilation.Create("..\\..\\RelativePath", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); // other characters than directory and volume separators are ok: CSharpCompilation.Create(@";,*?<>#!@&", options: compilationOptions).VerifyEmitDiagnostics(); CSharpCompilation.Create("goo", options: compilationOptions).VerifyEmitDiagnostics(); CSharpCompilation.Create(".goo", options: compilationOptions).VerifyEmitDiagnostics(); CSharpCompilation.Create("goo ", options: compilationOptions).VerifyEmitDiagnostics(); // can end with whitespace CSharpCompilation.Create("....", options: compilationOptions).VerifyEmitDiagnostics(); CSharpCompilation.Create(null, options: compilationOptions).VerifyEmitDiagnostics(); } [Fact] public void CreateAPITest() { var listSyntaxTree = new List<SyntaxTree>(); var listRef = new List<MetadataReference>(); var s1 = @"using Goo; namespace A.B { class C { class D { class E { } } } class G<T> { class Q<S1,S2> { } } class G<T1,T2> { } }"; SyntaxTree t1 = SyntaxFactory.ParseSyntaxTree(s1); listSyntaxTree.Add(t1); // System.dll listRef.Add(Net451.System.WithEmbedInteropTypes(true)); var ops = TestOptions.ReleaseExe; // Create Compilation with Option is not null var comp = CSharpCompilation.Create("Compilation", listSyntaxTree, listRef, ops); Assert.Equal(ops, comp.Options); Assert.NotEqual(default, comp.SyntaxTrees); Assert.NotNull(comp.References); Assert.Equal(1, comp.SyntaxTrees.Length); Assert.Equal(1, comp.ExternalReferences.Length); var ref1 = comp.ExternalReferences[0]; Assert.True(ref1.Properties.EmbedInteropTypes); Assert.True(ref1.Properties.Aliases.IsEmpty); // Create Compilation with PreProcessorSymbols of Option is empty var ops1 = TestOptions.DebugExe; // Create Compilation with Assembly name contains invalid char var asmname = "ÃÃâ€Â"; comp = CSharpCompilation.Create(asmname, listSyntaxTree, listRef, ops); var comp1 = CSharpCompilation.Create(asmname, listSyntaxTree, listRef, null); } [Fact] public void EmitToNonWritableStreams() { var peStream = new TestStream(canRead: false, canSeek: false, canWrite: false); var pdbStream = new TestStream(canRead: false, canSeek: false, canWrite: false); var c = CSharpCompilation.Create("a", new[] { SyntaxFactory.ParseSyntaxTree("class C { static void Main() {} }") }, new[] { MscorlibRef }); Assert.Throws<ArgumentException>(() => c.Emit(peStream)); Assert.Throws<ArgumentException>(() => c.Emit(new MemoryStream(), pdbStream)); } [Fact] public void EmitOptionsDiagnostics() { var c = CreateCompilation("class C {}"); var stream = new MemoryStream(); var options = new EmitOptions( debugInformationFormat: (DebugInformationFormat)(-1), outputNameOverride: " ", fileAlignment: 513, subsystemVersion: SubsystemVersion.Create(1000000, -1000000), pdbChecksumAlgorithm: new HashAlgorithmName("invalid hash algorithm name")); EmitResult result = c.Emit(stream, options: options); result.Diagnostics.Verify( // error CS2042: Invalid debug information format: -1 Diagnostic(ErrorCode.ERR_InvalidDebugInformationFormat).WithArguments("-1").WithLocation(1, 1), // error CS2041: Invalid output name: Name cannot start with whitespace. Diagnostic(ErrorCode.ERR_InvalidOutputName).WithArguments("Name cannot start with whitespace.").WithLocation(1, 1), // error CS2024: Invalid file section alignment '513' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("513").WithLocation(1, 1), // error CS1773: Invalid version 1000000.-1000000 for /subsystemversion. The version must be 6.02 or greater for ARM or AppContainerExe, and 4.00 or greater otherwise Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("1000000.-1000000").WithLocation(1, 1), // error CS8113: Invalid hash algorithm name: 'invalid hash algorithm name' Diagnostic(ErrorCode.ERR_InvalidHashAlgorithmName).WithArguments("invalid hash algorithm name").WithLocation(1, 1)); Assert.False(result.Success); } [Fact] public void EmitOptions_PdbChecksumAndDeterminism() { var options = new EmitOptions(pdbChecksumAlgorithm: default(HashAlgorithmName)); var diagnosticBag = new DiagnosticBag(); options.ValidateOptions(diagnosticBag, MessageProvider.Instance, isDeterministic: true); diagnosticBag.Verify( // error CS8113: Invalid hash algorithm name: '' Diagnostic(ErrorCode.ERR_InvalidHashAlgorithmName).WithArguments("")); diagnosticBag.Clear(); options.ValidateOptions(diagnosticBag, MessageProvider.Instance, isDeterministic: false); diagnosticBag.Verify(); } [Fact] public void Emit_BadArgs() { var comp = CSharpCompilation.Create("Compilation", options: TestOptions.ReleaseDll); Assert.Throws<ArgumentNullException>("peStream", () => comp.Emit(peStream: null)); Assert.Throws<ArgumentException>("peStream", () => comp.Emit(peStream: new TestStream(canRead: true, canWrite: false, canSeek: true))); Assert.Throws<ArgumentException>("pdbStream", () => comp.Emit(peStream: new MemoryStream(), pdbStream: new TestStream(canRead: true, canWrite: false, canSeek: true))); Assert.Throws<ArgumentException>("pdbStream", () => comp.Emit(peStream: new MemoryStream(), pdbStream: new MemoryStream(), options: EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.Embedded))); Assert.Throws<ArgumentException>("sourceLinkStream", () => comp.Emit( peStream: new MemoryStream(), pdbStream: new MemoryStream(), options: EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), sourceLinkStream: new TestStream(canRead: false, canWrite: true, canSeek: true))); Assert.Throws<ArgumentException>("embeddedTexts", () => comp.Emit( peStream: new MemoryStream(), pdbStream: null, options: null, embeddedTexts: new[] { EmbeddedText.FromStream("_", new MemoryStream()) })); Assert.Throws<ArgumentException>("embeddedTexts", () => comp.Emit( peStream: new MemoryStream(), pdbStream: null, options: EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), embeddedTexts: new[] { EmbeddedText.FromStream("_", new MemoryStream()) })); Assert.Throws<ArgumentException>("win32Resources", () => comp.Emit( peStream: new MemoryStream(), win32Resources: new TestStream(canRead: true, canWrite: false, canSeek: false))); Assert.Throws<ArgumentException>("win32Resources", () => comp.Emit( peStream: new MemoryStream(), win32Resources: new TestStream(canRead: false, canWrite: false, canSeek: true))); // we don't report an error when we can't write to the XML doc stream: Assert.True(comp.Emit( peStream: new MemoryStream(), pdbStream: new MemoryStream(), xmlDocumentationStream: new TestStream(canRead: true, canWrite: false, canSeek: true)).Success); } [Fact] public void ReferenceAPITest() { var opt = TestOptions.DebugExe; // Create Compilation takes two args var comp = CSharpCompilation.Create("Compilation", options: TestOptions.DebugExe); var ref1 = Net451.mscorlib; var ref2 = Net451.System; var ref3 = new TestMetadataReference(fullPath: @"c:\xml.bms"); var ref4 = new TestMetadataReference(fullPath: @"c:\aaa.dll"); // Add a new empty item comp = comp.AddReferences(Enumerable.Empty<MetadataReference>()); Assert.Equal(0, comp.ExternalReferences.Length); // Add a new valid item comp = comp.AddReferences(ref1); var assemblySmb = comp.GetReferencedAssemblySymbol(ref1); Assert.NotNull(assemblySmb); Assert.Equal("mscorlib", assemblySmb.Name, StringComparer.OrdinalIgnoreCase); Assert.Equal(1, comp.ExternalReferences.Length); Assert.Equal(MetadataImageKind.Assembly, comp.ExternalReferences[0].Properties.Kind); Assert.Equal(ref1, comp.ExternalReferences[0]); // Replace an existing item with another valid item comp = comp.ReplaceReference(ref1, ref2); Assert.Equal(1, comp.ExternalReferences.Length); Assert.Equal(MetadataImageKind.Assembly, comp.ExternalReferences[0].Properties.Kind); Assert.Equal(ref2, comp.ExternalReferences[0]); // Remove an existing item comp = comp.RemoveReferences(ref2); Assert.Equal(0, comp.ExternalReferences.Length); // Overload with Hashset var hs = new HashSet<MetadataReference> { ref1, ref2, ref3 }; var compCollection = CSharpCompilation.Create("Compilation", references: hs, options: opt); compCollection = compCollection.AddReferences(ref1, ref2, ref3, ref4).RemoveReferences(hs); Assert.Equal(1, compCollection.ExternalReferences.Length); compCollection = compCollection.AddReferences(hs).RemoveReferences(ref1, ref2, ref3, ref4); Assert.Equal(0, compCollection.ExternalReferences.Length); // Overload with Collection var col = new Collection<MetadataReference> { ref1, ref2, ref3 }; compCollection = CSharpCompilation.Create("Compilation", references: col, options: opt); compCollection = compCollection.AddReferences(col).RemoveReferences(ref1, ref2, ref3); Assert.Equal(0, compCollection.ExternalReferences.Length); compCollection = compCollection.AddReferences(ref1, ref2, ref3).RemoveReferences(col); Assert.Equal(0, comp.ExternalReferences.Length); // Overload with ConcurrentStack var stack = new ConcurrentStack<MetadataReference> { }; stack.Push(ref1); stack.Push(ref2); stack.Push(ref3); compCollection = CSharpCompilation.Create("Compilation", references: stack, options: opt); compCollection = compCollection.AddReferences(stack).RemoveReferences(ref1, ref3, ref2); Assert.Equal(0, compCollection.ExternalReferences.Length); compCollection = compCollection.AddReferences(ref2, ref1, ref3).RemoveReferences(stack); Assert.Equal(0, compCollection.ExternalReferences.Length); // Overload with ConcurrentQueue var queue = new ConcurrentQueue<MetadataReference> { }; queue.Enqueue(ref1); queue.Enqueue(ref2); queue.Enqueue(ref3); compCollection = CSharpCompilation.Create("Compilation", references: queue, options: opt); compCollection = compCollection.AddReferences(queue).RemoveReferences(ref3, ref2, ref1); Assert.Equal(0, compCollection.ExternalReferences.Length); compCollection = compCollection.AddReferences(ref2, ref1, ref3).RemoveReferences(queue); Assert.Equal(0, compCollection.ExternalReferences.Length); } [Fact] public void ReferenceDirectiveTests() { var t1 = Parse(@" #r ""a.dll"" #r ""a.dll"" ", filename: "1.csx", options: TestOptions.Script); var rd1 = t1.GetRoot().GetDirectives().Cast<ReferenceDirectiveTriviaSyntax>().ToArray(); Assert.Equal(2, rd1.Length); var t2 = Parse(@" #r ""a.dll"" #r ""b.dll"" ", options: TestOptions.Script); var rd2 = t2.GetRoot().GetDirectives().Cast<ReferenceDirectiveTriviaSyntax>().ToArray(); Assert.Equal(2, rd2.Length); var t3 = Parse(@" #r ""a.dll"" ", filename: "1.csx", options: TestOptions.Script); var rd3 = t3.GetRoot().GetDirectives().Cast<ReferenceDirectiveTriviaSyntax>().ToArray(); Assert.Equal(1, rd3.Length); var t4 = Parse(@" #r ""a.dll"" ", filename: "4.csx", options: TestOptions.Script); var rd4 = t4.GetRoot().GetDirectives().Cast<ReferenceDirectiveTriviaSyntax>().ToArray(); Assert.Equal(1, rd4.Length); var c = CreateCompilationWithMscorlib45(new[] { t1, t2 }, options: TestOptions.ReleaseDll.WithMetadataReferenceResolver( new TestMetadataReferenceResolver(files: new Dictionary<string, PortableExecutableReference>() { { @"a.dll", Net451.MicrosoftCSharp }, { @"b.dll", Net451.MicrosoftVisualBasic }, }))); c.VerifyDiagnostics(); // same containing script file name and directive string Assert.Same(Net451.MicrosoftCSharp, c.GetDirectiveReference(rd1[0])); Assert.Same(Net451.MicrosoftCSharp, c.GetDirectiveReference(rd1[1])); Assert.Same(Net451.MicrosoftCSharp, c.GetDirectiveReference(rd2[0])); Assert.Same(Net451.MicrosoftVisualBasic, c.GetDirectiveReference(rd2[1])); Assert.Same(Net451.MicrosoftCSharp, c.GetDirectiveReference(rd3[0])); // different script name or directive string: Assert.Null(c.GetDirectiveReference(rd4[0])); } [Fact, WorkItem(530131, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530131")] public void MetadataReferenceWithInvalidAlias() { var refcomp = CSharpCompilation.Create("DLL", options: TestOptions.ReleaseDll, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree("public class C {}") }, references: new MetadataReference[] { MscorlibRef }); var mtref = refcomp.EmitToImageReference(aliases: ImmutableArray.Create("a", "Alias(*#$@^%*&)")); // not use exported type var comp = CSharpCompilation.Create("APP", options: TestOptions.ReleaseDll, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree( @"class D {}" ) }, references: new MetadataReference[] { MscorlibRef, mtref } ); Assert.Empty(comp.GetDiagnostics()); // use exported type with partial alias comp = CSharpCompilation.Create("APP1", options: TestOptions.ReleaseDll, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree( @"extern alias Alias; class D : Alias::C {}" ) }, references: new MetadataReference[] { MscorlibRef, mtref } ); var errs = comp.GetDiagnostics(); // error CS0430: The extern alias 'Alias' was not specified in a /reference option Assert.Equal(430, errs.FirstOrDefault().Code); // use exported type with invalid alias comp = CSharpCompilation.Create("APP2", options: TestOptions.ReleaseExe, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree( "extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {}", options: TestOptions.Regular9) }, references: new MetadataReference[] { MscorlibRef, mtref } ); comp.VerifyDiagnostics( // (1,21): error CS1040: Preprocessor directives must appear as the first non-whitespace character on a line // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_BadDirectivePlacement, "#").WithLocation(1, 21), // (1,61): error CS1026: ) expected // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(1, 61), // (1,61): error CS1002: ; expected // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 61), // (1,14): error CS8112: Local function 'Alias()' must declare a body because it is not marked 'static extern'. // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "Alias").WithArguments("Alias()").WithLocation(1, 14), // (1,8): error CS0246: The type or namespace name 'alias' could not be found (are you missing a using directive or an assembly reference?) // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias").WithArguments("alias").WithLocation(1, 8), // (1,14): warning CS0626: Method, operator, or accessor 'Alias()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "Alias").WithArguments("Alias()").WithLocation(1, 14), // (1,14): warning CS8321: The local function 'Alias' is declared but never used // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Alias").WithArguments("Alias").WithLocation(1, 14) ); } [Fact, WorkItem(530131, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530131")] public void MetadataReferenceWithInvalidAliasWithCSharp6() { var refcomp = CSharpCompilation.Create("DLL", options: TestOptions.ReleaseDll, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree("public class C {}", options: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)) }, references: new MetadataReference[] { MscorlibRef }); var mtref = refcomp.EmitToImageReference(aliases: ImmutableArray.Create("a", "Alias(*#$@^%*&)")); // not use exported type var comp = CSharpCompilation.Create("APP", options: TestOptions.ReleaseDll, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree( @"class D {}", options: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)) }, references: new MetadataReference[] { MscorlibRef, mtref } ); Assert.Empty(comp.GetDiagnostics()); // use exported type with partial alias comp = CSharpCompilation.Create("APP1", options: TestOptions.ReleaseDll, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree( @"extern alias Alias; class D : Alias::C {}", options: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)) }, references: new MetadataReference[] { MscorlibRef, mtref } ); var errs = comp.GetDiagnostics(); // error CS0430: The extern alias 'Alias' was not specified in a /reference option Assert.Equal(430, errs.FirstOrDefault().Code); // use exported type with invalid alias comp = CSharpCompilation.Create("APP2", options: TestOptions.ReleaseExe, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree( "extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {}", options: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)) }, references: new MetadataReference[] { MscorlibRef, mtref } ); comp.VerifyDiagnostics( // (1,1): error CS8059: Feature 'top-level statements' is not available in C# 6. Please use language version 9.0 or greater. // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {}").WithArguments("top-level statements", "9.0").WithLocation(1, 1), // (1,1): error CS8059: Feature 'extern local functions' is not available in C# 6. Please use language version 9.0 or greater. // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "extern").WithArguments("extern local functions", "9.0").WithLocation(1, 1), // (1,14): error CS8059: Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater. // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "Alias").WithArguments("local functions", "7.0").WithLocation(1, 14), // (1,21): error CS1040: Preprocessor directives must appear as the first non-whitespace character on a line // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_BadDirectivePlacement, "#").WithLocation(1, 21), // (1,61): error CS1026: ) expected // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(1, 61), // (1,61): error CS1002: ; expected // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 61), // (1,14): error CS8112: Local function 'Alias()' must declare a body because it is not marked 'static extern'. // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "Alias").WithArguments("Alias()").WithLocation(1, 14), // (1,8): error CS0246: The type or namespace name 'alias' could not be found (are you missing a using directive or an assembly reference?) // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias").WithArguments("alias").WithLocation(1, 8), // (1,14): warning CS0626: Method, operator, or accessor 'Alias()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "Alias").WithArguments("Alias()").WithLocation(1, 14), // (1,14): warning CS8321: The local function 'Alias' is declared but never used // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Alias").WithArguments("Alias").WithLocation(1, 14) ); } [Fact] public void SyntreeAPITest() { var s1 = "namespace System.Linq {}"; var s2 = @" namespace NA.NB { partial class C<T> { public partial class D { intttt F; } } class C { } } "; var s3 = @"int x;"; var s4 = @"Imports System "; var s5 = @" class D { public static int Goo() { long l = 25l; return 0; } } "; SyntaxTree t1 = SyntaxFactory.ParseSyntaxTree(s1); SyntaxTree withErrorTree = SyntaxFactory.ParseSyntaxTree(s2); SyntaxTree withErrorTree1 = SyntaxFactory.ParseSyntaxTree(s3); SyntaxTree withErrorTreeVB = SyntaxFactory.ParseSyntaxTree(s4); SyntaxTree withExpressionRootTree = SyntaxFactory.ParseExpression(s3).SyntaxTree; var withWarning = SyntaxFactory.ParseSyntaxTree(s5); // Create compilation takes three args var comp = CSharpCompilation.Create("Compilation", syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree(s1) }, options: TestOptions.ReleaseDll); comp = comp.AddSyntaxTrees(t1, withErrorTree, withErrorTree1, withErrorTreeVB); Assert.Equal(5, comp.SyntaxTrees.Length); comp = comp.RemoveSyntaxTrees(t1, withErrorTree, withErrorTree1, withErrorTreeVB); Assert.Equal(1, comp.SyntaxTrees.Length); // Add a new empty item comp = comp.AddSyntaxTrees(Enumerable.Empty<SyntaxTree>()); Assert.Equal(1, comp.SyntaxTrees.Length); // Add a new valid item comp = comp.AddSyntaxTrees(t1); Assert.Equal(2, comp.SyntaxTrees.Length); Assert.Contains(t1, comp.SyntaxTrees); Assert.False(comp.SyntaxTrees.Contains(SyntaxFactory.ParseSyntaxTree(s1))); comp = comp.AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(s1)); Assert.Equal(3, comp.SyntaxTrees.Length); // Replace an existing item with another valid item comp = comp.ReplaceSyntaxTree(t1, SyntaxFactory.ParseSyntaxTree(s1)); Assert.Equal(3, comp.SyntaxTrees.Length); // Replace an existing item with same item comp = comp.AddSyntaxTrees(t1).ReplaceSyntaxTree(t1, t1); Assert.Equal(4, comp.SyntaxTrees.Length); // add again and verify that it throws Assert.Throws<ArgumentException>(() => comp.AddSyntaxTrees(t1)); // replace with existing and verify that it throws Assert.Throws<ArgumentException>(() => comp.ReplaceSyntaxTree(t1, comp.SyntaxTrees[0])); // SyntaxTrees have reference equality. This removal should fail. Assert.Throws<ArgumentException>(() => comp = comp.RemoveSyntaxTrees(SyntaxFactory.ParseSyntaxTree(s1))); Assert.Equal(4, comp.SyntaxTrees.Length); // Remove non-existing item Assert.Throws<ArgumentException>(() => comp = comp.RemoveSyntaxTrees(withErrorTree)); Assert.Equal(4, comp.SyntaxTrees.Length); // Add syntaxtree with error comp = comp.AddSyntaxTrees(withErrorTree1); var error = comp.GetDiagnostics(); Assert.InRange(comp.GetDiagnostics().Count(), 0, int.MaxValue); Assert.InRange(comp.GetDeclarationDiagnostics().Count(), 0, int.MaxValue); Assert.True(comp.SyntaxTrees.Contains(t1)); SyntaxTree t4 = SyntaxFactory.ParseSyntaxTree("Using System;"); SyntaxTree t5 = SyntaxFactory.ParseSyntaxTree("Usingsssssssssssss System;"); SyntaxTree t6 = SyntaxFactory.ParseSyntaxTree("Import System;"); // Overload with Hashset var hs = new HashSet<SyntaxTree> { t4, t5, t6 }; var compCollection = CSharpCompilation.Create("Compilation", syntaxTrees: hs); compCollection = compCollection.RemoveSyntaxTrees(hs); Assert.Equal(0, compCollection.SyntaxTrees.Length); compCollection = compCollection.AddSyntaxTrees(hs).RemoveSyntaxTrees(t4, t5, t6); Assert.Equal(0, compCollection.SyntaxTrees.Length); // Overload with Collection var col = new Collection<SyntaxTree> { t4, t5, t6 }; compCollection = CSharpCompilation.Create("Compilation", syntaxTrees: col); compCollection = compCollection.RemoveSyntaxTrees(t4, t5, t6); Assert.Equal(0, compCollection.SyntaxTrees.Length); Assert.Throws<ArgumentException>(() => compCollection = compCollection.AddSyntaxTrees(t4, t5).RemoveSyntaxTrees(col)); Assert.Equal(0, compCollection.SyntaxTrees.Length); // Overload with ConcurrentStack var stack = new ConcurrentStack<SyntaxTree> { }; stack.Push(t4); stack.Push(t5); stack.Push(t6); compCollection = CSharpCompilation.Create("Compilation", syntaxTrees: stack); compCollection = compCollection.RemoveSyntaxTrees(t4, t6, t5); Assert.Equal(0, compCollection.SyntaxTrees.Length); Assert.Throws<ArgumentException>(() => compCollection = compCollection.AddSyntaxTrees(t4, t6).RemoveSyntaxTrees(stack)); Assert.Equal(0, compCollection.SyntaxTrees.Length); // Overload with ConcurrentQueue var queue = new ConcurrentQueue<SyntaxTree> { }; queue.Enqueue(t4); queue.Enqueue(t5); queue.Enqueue(t6); compCollection = CSharpCompilation.Create("Compilation", syntaxTrees: queue); compCollection = compCollection.RemoveSyntaxTrees(t4, t6, t5); Assert.Equal(0, compCollection.SyntaxTrees.Length); Assert.Throws<ArgumentException>(() => compCollection = compCollection.AddSyntaxTrees(t4, t6).RemoveSyntaxTrees(queue)); Assert.Equal(0, compCollection.SyntaxTrees.Length); // Get valid binding var bind = comp.GetSemanticModel(syntaxTree: t1); Assert.Equal(t1, bind.SyntaxTree); Assert.Equal("C#", bind.Language); // Remove syntaxtree without error comp = comp.RemoveSyntaxTrees(t1); Assert.InRange(comp.GetDiagnostics().Count(), 0, int.MaxValue); // Remove syntaxtree with error comp = comp.RemoveSyntaxTrees(withErrorTree1); var e = comp.GetDiagnostics(cancellationToken: default(CancellationToken)); Assert.Equal(0, comp.GetDiagnostics(cancellationToken: default(CancellationToken)).Count()); // Add syntaxtree which is VB language comp = comp.AddSyntaxTrees(withErrorTreeVB); error = comp.GetDiagnostics(cancellationToken: CancellationToken.None); Assert.InRange(comp.GetDiagnostics().Count(), 0, int.MaxValue); comp = comp.RemoveSyntaxTrees(withErrorTreeVB); Assert.Equal(0, comp.GetDiagnostics().Count()); // Add syntaxtree with error comp = comp.AddSyntaxTrees(withWarning); error = comp.GetDeclarationDiagnostics(); Assert.InRange(error.Count(), 1, int.MaxValue); comp = comp.RemoveSyntaxTrees(withWarning); Assert.Equal(0, comp.GetDiagnostics().Count()); // Compilation.Create with syntaxtree with a non-CompilationUnit root node: should throw an ArgumentException. Assert.False(withExpressionRootTree.HasCompilationUnitRoot, "how did we get a CompilationUnit root?"); Assert.Throws<ArgumentException>(() => CSharpCompilation.Create("Compilation", new SyntaxTree[] { withExpressionRootTree })); // AddSyntaxTrees with a non-CompilationUnit root node: should throw an ArgumentException. Assert.Throws<ArgumentException>(() => comp.AddSyntaxTrees(withExpressionRootTree)); // ReplaceSyntaxTrees syntaxtree with a non-CompilationUnit root node: should throw an ArgumentException. Assert.Throws<ArgumentException>(() => comp.ReplaceSyntaxTree(comp.SyntaxTrees[0], withExpressionRootTree)); } [Fact] public void ChainedOperations() { var s1 = "using System.Linq;"; var s2 = ""; var s3 = "Import System"; SyntaxTree t1 = SyntaxFactory.ParseSyntaxTree(s1); SyntaxTree t2 = SyntaxFactory.ParseSyntaxTree(s2); SyntaxTree t3 = SyntaxFactory.ParseSyntaxTree(s3); var listSyntaxTree = new List<SyntaxTree>(); listSyntaxTree.Add(t1); listSyntaxTree.Add(t2); // Remove second SyntaxTree CSharpCompilation comp = CSharpCompilation.Create(options: TestOptions.ReleaseDll, assemblyName: "Compilation", references: null, syntaxTrees: null); comp = comp.AddSyntaxTrees(listSyntaxTree).RemoveSyntaxTrees(t2); Assert.Equal(1, comp.SyntaxTrees.Length); // Remove mid SyntaxTree listSyntaxTree.Add(t3); comp = comp.RemoveSyntaxTrees(t1).AddSyntaxTrees(listSyntaxTree).RemoveSyntaxTrees(t2); Assert.Equal(2, comp.SyntaxTrees.Length); // remove list listSyntaxTree.Remove(t2); comp = comp.AddSyntaxTrees().RemoveSyntaxTrees(listSyntaxTree); comp = comp.AddSyntaxTrees(listSyntaxTree).RemoveSyntaxTrees(listSyntaxTree); Assert.Equal(0, comp.SyntaxTrees.Length); listSyntaxTree.Clear(); listSyntaxTree.Add(t1); listSyntaxTree.Add(t1); // Chained operation count > 2 Assert.Throws<ArgumentException>(() => comp = comp.AddSyntaxTrees(listSyntaxTree).AddReferences().ReplaceSyntaxTree(t1, t2)); comp = comp.AddSyntaxTrees(t1).AddReferences().ReplaceSyntaxTree(t1, t2); Assert.Equal(1, comp.SyntaxTrees.Length); Assert.Equal(0, comp.ExternalReferences.Length); // Create compilation with args is disordered CSharpCompilation comp1 = CSharpCompilation.Create(assemblyName: "Compilation", syntaxTrees: null, options: TestOptions.ReleaseDll, references: null); var ref1 = Net451.mscorlib; var listRef = new List<MetadataReference>(); listRef.Add(ref1); listRef.Add(ref1); // Remove with no args comp1 = comp1.AddReferences(listRef).AddSyntaxTrees(t1).RemoveReferences().RemoveSyntaxTrees(); Assert.Equal(1, comp1.ExternalReferences.Length); Assert.Equal(1, comp1.SyntaxTrees.Length); } [WorkItem(713356, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/713356")] [ClrOnlyFact] public void MissedModuleA() { var netModule1 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a1", source: new string[] { "public class C1 {}" }); netModule1.VerifyEmitDiagnostics(); var netModule2 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a2", references: new MetadataReference[] { netModule1.EmitToImageReference() }, source: new string[] { @" public class C2 { public static void M() { var a = new C1(); } }" }); netModule2.VerifyEmitDiagnostics(); var assembly = CreateCompilation( options: TestOptions.ReleaseExe, assemblyName: "a", references: new MetadataReference[] { netModule2.EmitToImageReference() }, source: new string[] { @" public class C3 { public static void Main(string[] args) { var a = new C2(); } }" }); assembly.VerifyEmitDiagnostics( Diagnostic(ErrorCode.ERR_MissingNetModuleReference).WithArguments("a1.netmodule")); assembly = CreateCompilation( options: TestOptions.ReleaseExe, assemblyName: "a", references: new MetadataReference[] { netModule1.EmitToImageReference(), netModule2.EmitToImageReference() }, source: new string[] { @" public class C3 { public static void Main(string[] args) { var a = new C2(); } }" }); assembly.VerifyEmitDiagnostics(); CompileAndVerify(assembly); } [WorkItem(713356, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/713356")] [Fact] public void MissedModuleB_OneError() { var netModule1 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a1", source: new string[] { "public class C1 {}" }); netModule1.VerifyEmitDiagnostics(); var netModule2 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a2", references: new MetadataReference[] { netModule1.EmitToImageReference() }, source: new string[] { @" public class C2 { public static void M() { var a = new C1(); } }" }); netModule2.VerifyEmitDiagnostics(); var netModule3 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a3", references: new MetadataReference[] { netModule1.EmitToImageReference() }, source: new string[] { @" public class C2a { public static void M() { var a = new C1(); } }" }); netModule3.VerifyEmitDiagnostics(); var assembly = CreateCompilation( options: TestOptions.ReleaseExe, assemblyName: "a", references: new MetadataReference[] { netModule2.EmitToImageReference(), netModule3.EmitToImageReference() }, source: new string[] { @" public class C3 { public static void Main(string[] args) { var a = new C2(); } }" }); assembly.VerifyEmitDiagnostics( Diagnostic(ErrorCode.ERR_MissingNetModuleReference).WithArguments("a1.netmodule")); } [WorkItem(718500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718500")] [WorkItem(716762, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/716762")] [Fact] public void MissedModuleB_NoErrorForUnmanagedModules() { var netModule1 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a1", source: new string[] { @" using System; using System.Runtime.InteropServices; public class C2 { [DllImport(""user32.dll"", CharSet = CharSet.Unicode)] public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); }" }); netModule1.VerifyEmitDiagnostics(); var assembly = CreateCompilation( options: TestOptions.ReleaseExe, assemblyName: "a", references: new MetadataReference[] { netModule1.EmitToImageReference() }, source: new string[] { @" public class C3 { public static void Main(string[] args) { var a = new C2(); } }" }); assembly.VerifyEmitDiagnostics(); } [WorkItem(715872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715872")] [Fact] public void MissedModuleC() { var netModule1 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a1", source: new string[] { "public class C1 {}" }); netModule1.VerifyEmitDiagnostics(); var netModule2 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a1", references: new MetadataReference[] { netModule1.EmitToImageReference() }, source: new string[] { @" public class C2 { public static void M() { var a = new C1(); } }" }); netModule2.VerifyEmitDiagnostics(); var assembly = CreateCompilation( options: TestOptions.ReleaseExe, assemblyName: "a", references: new MetadataReference[] { netModule1.EmitToImageReference(), netModule2.EmitToImageReference() }, source: new string[] { @" public class C3 { public static void Main(string[] args) { var a = new C2(); } }" }); assembly.VerifyEmitDiagnostics(Diagnostic(ErrorCode.ERR_NetModuleNameMustBeUnique).WithArguments("a1.netmodule")); } [Fact] public void MixedRefType() { var vbComp = VB.VisualBasicCompilation.Create("CompilationVB"); var comp = CSharpCompilation.Create("Compilation"); vbComp = vbComp.AddReferences(SystemRef); // Add VB reference to C# compilation foreach (var item in vbComp.References) { comp = comp.AddReferences(item); comp = comp.ReplaceReference(item, item); } Assert.Equal(1, comp.ExternalReferences.Length); var text1 = @"class A {}"; var comp1 = CSharpCompilation.Create("Test1", new[] { SyntaxFactory.ParseSyntaxTree(text1) }); var comp2 = CSharpCompilation.Create("Test2", new[] { SyntaxFactory.ParseSyntaxTree(text1) }); var compRef1 = comp1.ToMetadataReference(); var compRef2 = comp2.ToMetadataReference(); var compRef = vbComp.ToMetadataReference(embedInteropTypes: true); var ref1 = Net451.mscorlib; var ref2 = Net451.System; // Add CompilationReference comp = CSharpCompilation.Create( "Test1", new[] { SyntaxFactory.ParseSyntaxTree(text1) }, new MetadataReference[] { compRef1, compRef2 }); Assert.Equal(2, comp.ExternalReferences.Length); Assert.True(comp.References.Contains(compRef1)); Assert.True(comp.References.Contains(compRef2)); var smb = comp.GetReferencedAssemblySymbol(compRef1); Assert.Equal(SymbolKind.Assembly, smb.Kind); Assert.Equal("Test1", smb.Identity.Name, StringComparer.OrdinalIgnoreCase); // Mixed reference type comp = comp.AddReferences(ref1); Assert.Equal(3, comp.ExternalReferences.Length); Assert.True(comp.References.Contains(ref1)); // Replace Compilation reference with Assembly file reference comp = comp.ReplaceReference(compRef2, ref2); Assert.Equal(3, comp.ExternalReferences.Length); Assert.True(comp.References.Contains(ref2)); // Replace Assembly file reference with Compilation reference comp = comp.ReplaceReference(ref1, compRef2); Assert.Equal(3, comp.ExternalReferences.Length); Assert.True(comp.References.Contains(compRef2)); var modRef1 = TestReferences.MetadataTests.NetModule01.ModuleCS00; // Add Module file reference comp = comp.AddReferences(modRef1); // Not implemented code //var modSmb = comp.GetReferencedModuleSymbol(modRef1); //Assert.Equal("ModuleCS00.mod", modSmb.Name); //Assert.Equal(4, comp.References.Count); //Assert.True(comp.References.Contains(modRef1)); //smb = comp.GetReferencedAssemblySymbol(reference: modRef1); //Assert.Equal(smb.Kind, SymbolKind.Assembly); //Assert.Equal("Test1", smb.Identity.Name, StringComparer.OrdinalIgnoreCase); // GetCompilationNamespace Not implemented(Derived Class AssemblySymbol) //var m = smb.GlobalNamespace.GetMembers(); //var nsSmb = smb.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; //var ns = comp.GetCompilationNamespace(ns: nsSmb); //Assert.Equal(ns.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); //var asbSmb = smb as Symbol; //var ns1 = comp.GetCompilationNamespace(ns: asbSmb as NamespaceSymbol); //Assert.Equal(ns1.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns1.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); // Get Referenced Module Symbol //var moduleSmb = comp.GetReferencedModuleSymbol(reference: modRef1); //Assert.Equal(SymbolKind.NetModule, moduleSmb.Kind); //Assert.Equal("ModuleCS00.mod", moduleSmb.Name, StringComparer.OrdinalIgnoreCase); // GetCompilationNamespace Not implemented(Derived Class ModuleSymbol) //nsSmb = moduleSmb.GlobalNamespace.GetMembers("Runtime").Single() as NamespaceSymbol; //ns = comp.GetCompilationNamespace(ns: nsSmb); //Assert.Equal(ns.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); //var modSmbol = moduleSmb as Symbol; //ns1 = comp.GetCompilationNamespace(ns: modSmbol as NamespaceSymbol); //Assert.Equal(ns1.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns1.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); // Get Compilation Namespace //nsSmb = comp.GlobalNamespace; //ns = comp.GetCompilationNamespace(ns: nsSmb); //Assert.Equal(ns.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); // GetCompilationNamespace Not implemented(Derived Class MergedNamespaceSymbol) //NamespaceSymbol merged = MergedNamespaceSymbol.Create(new NamespaceExtent(new MockAssemblySymbol("Merged")), null, null); //ns = comp.GetCompilationNamespace(ns: merged); //Assert.Equal(ns.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); // GetCompilationNamespace Not implemented(Derived Class RetargetingNamespaceSymbol) //Retargeting.RetargetingNamespaceSymbol retargetSmb = nsSmb as Retargeting.RetargetingNamespaceSymbol; //ns = comp.GetCompilationNamespace(ns: retargetSmb); //Assert.Equal(ns.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); // GetCompilationNamespace Not implemented(Derived Class PENamespaceSymbol) //Symbols.Metadata.PE.PENamespaceSymbol pensSmb = nsSmb as Symbols.Metadata.PE.PENamespaceSymbol; //ns = comp.GetCompilationNamespace(ns: pensSmb); //Assert.Equal(ns.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); // Replace Module file reference with compilation reference comp = comp.RemoveReferences(compRef1).ReplaceReference(modRef1, compRef1); Assert.Equal(3, comp.ExternalReferences.Length); // Check the reference order after replace Assert.True(comp.ExternalReferences[2] is CSharpCompilationReference, "Expected compilation reference"); Assert.Equal(compRef1, comp.ExternalReferences[2]); // Replace compilation Module file reference with Module file reference comp = comp.ReplaceReference(compRef1, modRef1); // Check the reference order after replace Assert.Equal(3, comp.ExternalReferences.Length); Assert.Equal(MetadataImageKind.Module, comp.ExternalReferences[2].Properties.Kind); Assert.Equal(modRef1, comp.ExternalReferences[2]); // Add VB compilation ref Assert.Throws<ArgumentException>(() => comp.AddReferences(compRef)); foreach (var item in comp.References) { comp = comp.RemoveReferences(item); } Assert.Equal(0, comp.ExternalReferences.Length); // Not Implemented // var asmByteRef = MetadataReference.CreateFromImage(new byte[5], embedInteropTypes: true); //var asmObjectRef = new AssemblyObjectReference(assembly: System.Reflection.Assembly.GetAssembly(typeof(object)),embedInteropTypes :true); //comp =comp.AddReferences(asmByteRef, asmObjectRef); //Assert.Equal(2, comp.References.Count); //Assert.Equal(ReferenceKind.AssemblyBytes, comp.References[0].Kind); //Assert.Equal(ReferenceKind.AssemblyObject , comp.References[1].Kind); //Assert.Equal(asmByteRef, comp.References[0]); //Assert.Equal(asmObjectRef, comp.References[1]); //Assert.True(comp.References[0].EmbedInteropTypes); //Assert.True(comp.References[1].EmbedInteropTypes); } [Fact] public void NegGetCompilationNamespace() { var comp = CSharpCompilation.Create("Compilation"); // Throw exception when the parameter of GetCompilationNamespace is null Assert.Throws<NullReferenceException>( delegate { comp.GetCompilationNamespace(namespaceSymbol: (INamespaceSymbol)null); }); Assert.Throws<NullReferenceException>( delegate { comp.GetCompilationNamespace(namespaceSymbol: (NamespaceSymbol)null); }); } [WorkItem(537623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537623")] [Fact] public void NegCreateCompilation() { Assert.Throws<ArgumentNullException>(() => CSharpCompilation.Create("goo", syntaxTrees: new SyntaxTree[] { null })); Assert.Throws<ArgumentNullException>(() => CSharpCompilation.Create("goo", references: new MetadataReference[] { null })); } [WorkItem(537637, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537637")] [Fact] public void NegGetSymbol() { // Create Compilation with miss mid args var comp = CSharpCompilation.Create("Compilation"); Assert.Null(comp.GetReferencedAssemblySymbol(reference: MscorlibRef)); var modRef1 = TestReferences.MetadataTests.NetModule01.ModuleCS00; // Get not exist Referenced Module Symbol Assert.Null(comp.GetReferencedModuleSymbol(modRef1)); // Throw exception when the parameter of GetReferencedAssemblySymbol is null Assert.Throws<ArgumentNullException>( delegate { comp.GetReferencedAssemblySymbol(null); }); // Throw exception when the parameter of GetReferencedModuleSymbol is null Assert.Throws<ArgumentNullException>( delegate { var modSmb1 = comp.GetReferencedModuleSymbol(null); }); } [WorkItem(537778, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537778")] // Throw exception when the parameter of the parameter type of GetReferencedAssemblySymbol is VB.CompilationReference [Fact] public void NegGetSymbol1() { var opt = TestOptions.ReleaseDll; var comp = CSharpCompilation.Create("Compilation"); var vbComp = VB.VisualBasicCompilation.Create("CompilationVB"); vbComp = vbComp.AddReferences(SystemRef); var compRef = vbComp.ToMetadataReference(); Assert.Throws<ArgumentException>(() => comp.AddReferences(compRef)); // Throw exception when the parameter of GetBinding is null Assert.Throws<ArgumentNullException>( delegate { comp.GetSemanticModel(null); }); // Throw exception when the parameter of GetTypeByNameAndArity is NULL //Assert.Throws<Exception>( //delegate //{ // comp.GetTypeByNameAndArity(fullName: null, arity: 1); //}); // Throw exception when the parameter of GetTypeByNameAndArity is less than 0 //Assert.Throws<Exception>( //delegate //{ // comp.GetTypeByNameAndArity(string.Empty, -4); //}); } // Add already existing item [Fact, WorkItem(537574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537574")] public void NegReference2() { var ref1 = Net451.mscorlib; var ref2 = Net451.System; var ref3 = Net451.SystemData; var ref4 = Net451.SystemXml; var comp = CSharpCompilation.Create("Compilation"); comp = comp.AddReferences(ref1, ref1); Assert.Equal(1, comp.ExternalReferences.Length); Assert.Equal(MetadataImageKind.Assembly, comp.ExternalReferences[0].Properties.Kind); Assert.Equal(ref1, comp.ExternalReferences[0]); var listRef = new List<MetadataReference> { ref1, ref2, ref3, ref4 }; // Chained operation count > 3 // ReplaceReference throws if the reference to be replaced is not found. comp = comp.AddReferences(listRef).AddReferences(ref2).RemoveReferences(ref1, ref3, ref4).ReplaceReference(ref2, ref2); Assert.Equal(1, comp.ExternalReferences.Length); Assert.Equal(MetadataImageKind.Assembly, comp.ExternalReferences[0].Properties.Kind); Assert.Equal(ref2, comp.ExternalReferences[0]); Assert.Throws<ArgumentException>(() => comp.AddReferences(listRef).AddReferences(ref2).RemoveReferences(ref1, ref2, ref3, ref4).ReplaceReference(ref2, ref2)); } // Add a new invalid item [Fact, WorkItem(537575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537575")] public void NegReference3() { var ref1 = InvalidRef; var comp = CSharpCompilation.Create("Compilation"); // Remove non-existing item Assert.Throws<ArgumentException>(() => comp = comp.RemoveReferences(ref1)); // Add a new invalid item comp = comp.AddReferences(ref1); Assert.Equal(1, comp.ExternalReferences.Length); // Replace a non-existing item with another invalid item Assert.Throws<ArgumentException>(() => comp = comp.ReplaceReference(MscorlibRef, ref1)); Assert.Equal(1, comp.ExternalReferences.Length); } // Replace a non-existing item with null [Fact, WorkItem(537567, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537567")] public void NegReference4() { var ref1 = Net451.mscorlib; var comp = CSharpCompilation.Create("Compilation"); Assert.Throws<ArgumentException>( delegate { comp = comp.ReplaceReference(ref1, null); }); // Replace null and the arg order of replace is vise Assert.Throws<ArgumentNullException>( delegate { comp = comp.ReplaceReference(newReference: ref1, oldReference: null); }); } // Replace a non-existing item with another valid item [Fact, WorkItem(537566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537566")] public void NegReference5() { var ref1 = Net451.mscorlib; var ref2 = Net451.SystemXml; var comp = CSharpCompilation.Create("Compilation"); Assert.Throws<ArgumentException>( delegate { comp = comp.ReplaceReference(ref1, ref2); }); SyntaxTree t1 = SyntaxFactory.ParseSyntaxTree("Using System;"); // Replace a non-existing item with another valid item and disorder the args Assert.Throws<ArgumentException>( delegate { comp.ReplaceReference(newReference: Net451.System, oldReference: ref2); }); Assert.Equal(0, comp.SyntaxTrees.Length); Assert.Throws<ArgumentException>(() => comp.ReplaceSyntaxTree(newTree: SyntaxFactory.ParseSyntaxTree("Using System;"), oldTree: t1)); Assert.Equal(0, comp.SyntaxTrees.Length); } [WorkItem(527256, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527256")] // Throw exception when the parameter of SyntaxTrees.Contains is null [Fact] public void NegSyntaxTreesContains() { var comp = CSharpCompilation.Create("Compilation"); Assert.False(comp.SyntaxTrees.Contains(null)); } [WorkItem(537784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537784")] // Throw exception when the parameter of GetSpecialType() is out of range [Fact] public void NegGetSpecialType() { var comp = CSharpCompilation.Create("Compilation"); // Throw exception when the parameter of GetBinding is out of range Assert.Throws<ArgumentOutOfRangeException>( delegate { comp.GetSpecialType((SpecialType)100); }); Assert.Throws<ArgumentOutOfRangeException>( delegate { comp.GetSpecialType(SpecialType.None); }); Assert.Throws<ArgumentOutOfRangeException>( delegate { comp.GetSpecialType((SpecialType)000); }); Assert.Throws<ArgumentOutOfRangeException>( delegate { comp.GetSpecialType(default(SpecialType)); }); } [WorkItem(538168, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538168")] // Replace a non-existing item with another valid item and disorder the args [Fact] public void NegTree2() { var comp = CSharpCompilation.Create("API"); SyntaxTree t1 = SyntaxFactory.ParseSyntaxTree("Using System;"); Assert.Throws<ArgumentException>( delegate { comp = comp.ReplaceSyntaxTree(newTree: SyntaxFactory.ParseSyntaxTree("Using System;"), oldTree: t1); }); } [WorkItem(537576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537576")] // Add already existing item [Fact] public void NegSynTree1() { var comp = CSharpCompilation.Create("Compilation"); SyntaxTree t1 = SyntaxFactory.ParseSyntaxTree("Using System;"); Assert.Throws<ArgumentException>(() => (comp.AddSyntaxTrees(t1, t1))); Assert.Equal(0, comp.SyntaxTrees.Length); } [Fact] public void NegSynTree() { var comp = CSharpCompilation.Create("Compilation"); SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("Using Goo;"); // Throw exception when add null SyntaxTree Assert.Throws<ArgumentNullException>( delegate { comp.AddSyntaxTrees(null); }); // Throw exception when Remove null SyntaxTree Assert.Throws<ArgumentNullException>( delegate { comp.RemoveSyntaxTrees(null); }); // No exception when replacing a SyntaxTree with null var compP = comp.AddSyntaxTrees(syntaxTree); comp = compP.ReplaceSyntaxTree(syntaxTree, null); Assert.Equal(0, comp.SyntaxTrees.Length); // Throw exception when remove null SyntaxTree Assert.Throws<ArgumentNullException>( delegate { comp = comp.ReplaceSyntaxTree(null, syntaxTree); }); var s1 = "Imports System.Text"; SyntaxTree t1 = VB.VisualBasicSyntaxTree.ParseText(s1); SyntaxTree t2 = t1; var t3 = t2; var vbComp = VB.VisualBasicCompilation.Create("CompilationVB"); vbComp = vbComp.AddSyntaxTrees(t1, VB.VisualBasicSyntaxTree.ParseText("Using Goo;")); // Throw exception when cast SyntaxTree foreach (var item in vbComp.SyntaxTrees) { t3 = item; Exception invalidCastSynTreeEx = Assert.Throws<InvalidCastException>( delegate { comp = comp.AddSyntaxTrees(t3); }); invalidCastSynTreeEx = Assert.Throws<InvalidCastException>( delegate { comp = comp.RemoveSyntaxTrees(t3); }); invalidCastSynTreeEx = Assert.Throws<InvalidCastException>( delegate { comp = comp.ReplaceSyntaxTree(t3, t3); }); } // Get Binding with tree is not exist SyntaxTree t4 = SyntaxFactory.ParseSyntaxTree(s1); Assert.Throws<ArgumentException>( delegate { comp.RemoveSyntaxTrees(new SyntaxTree[] { t4 }).GetSemanticModel(t4); }); } [Fact] public void GetEntryPoint_Exe() { var source = @" class A { static void Main() { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var mainMethod = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMember<MethodSymbol>("Main"); Assert.Equal(mainMethod, compilation.GetEntryPoint(default(CancellationToken))); var entryPointAndDiagnostics = compilation.GetEntryPointAndDiagnostics(default(CancellationToken)); Assert.Equal(mainMethod, entryPointAndDiagnostics.MethodSymbol); entryPointAndDiagnostics.Diagnostics.Verify(); } [Fact] public void GetEntryPoint_Dll() { var source = @" class A { static void Main() { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); Assert.Null(compilation.GetEntryPoint(default(CancellationToken))); Assert.Same(CSharpCompilation.EntryPoint.None, compilation.GetEntryPointAndDiagnostics(default(CancellationToken))); } [Fact] public void GetEntryPoint_Module() { var source = @" class A { static void Main() { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseModule); compilation.VerifyDiagnostics(); Assert.Null(compilation.GetEntryPoint(default(CancellationToken))); Assert.Same(CSharpCompilation.EntryPoint.None, compilation.GetEntryPointAndDiagnostics(default(CancellationToken))); } [Fact] public void CreateCompilationForModule() { var source = @" class A { static void Main() { } } "; // equivalent of csc with no /moduleassemblyname specified: var compilation = CSharpCompilation.Create(assemblyName: null, options: TestOptions.ReleaseModule, syntaxTrees: new[] { Parse(source) }, references: new[] { MscorlibRef }); compilation.VerifyEmitDiagnostics(); Assert.Null(compilation.AssemblyName); Assert.Equal("?", compilation.Assembly.Name); Assert.Equal("?", compilation.Assembly.Identity.Name); // no name is allowed for assembly as well, although it isn't useful: compilation = CSharpCompilation.Create(assemblyName: null, options: TestOptions.ReleaseDll, syntaxTrees: new[] { Parse(source) }, references: new[] { MscorlibRef }); compilation.VerifyEmitDiagnostics(); Assert.Null(compilation.AssemblyName); Assert.Equal("?", compilation.Assembly.Name); Assert.Equal("?", compilation.Assembly.Identity.Name); // equivalent of csc with /moduleassemblyname specified: compilation = CSharpCompilation.Create(assemblyName: "ModuleAssemblyName", options: TestOptions.ReleaseModule, syntaxTrees: new[] { Parse(source) }, references: new[] { MscorlibRef }); compilation.VerifyDiagnostics(); Assert.Equal("ModuleAssemblyName", compilation.AssemblyName); Assert.Equal("ModuleAssemblyName", compilation.Assembly.Name); Assert.Equal("ModuleAssemblyName", compilation.Assembly.Identity.Name); } [WorkItem(8506, "https://github.com/dotnet/roslyn/issues/8506")] [WorkItem(17403, "https://github.com/dotnet/roslyn/issues/17403")] [Fact] public void CrossCorlibSystemObjectReturnType_Script() { // MinAsyncCorlibRef corlib is used since it provides just enough corlib type definitions // and Task APIs necessary for script hosting are provided by MinAsyncRef. This ensures that // `System.Object, mscorlib, Version=4.0.0.0` will not be provided (since it's unversioned). // // In the original bug, Xamarin iOS, Android, and Mac Mobile profile corlibs were // realistic cross-compilation targets. void AssertCompilationCorlib(CSharpCompilation compilation) { Assert.True(compilation.IsSubmission); var taskOfT = compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T); var taskOfObject = taskOfT.Construct(compilation.ObjectType); var entryPoint = compilation.GetEntryPoint(default(CancellationToken)); Assert.Same(compilation.ObjectType.ContainingAssembly, taskOfT.ContainingAssembly); Assert.Same(compilation.ObjectType.ContainingAssembly, taskOfObject.ContainingAssembly); Assert.Equal(taskOfObject, entryPoint.ReturnType); } var firstCompilation = CSharpCompilation.CreateScriptCompilation( "submission-assembly-1", references: new[] { MinAsyncCorlibRef }, syntaxTree: Parse("true", options: TestOptions.Script) ).VerifyDiagnostics(); AssertCompilationCorlib(firstCompilation); var secondCompilation = CSharpCompilation.CreateScriptCompilation( "submission-assembly-2", previousScriptCompilation: firstCompilation, syntaxTree: Parse("false", options: TestOptions.Script)) .WithScriptCompilationInfo(new CSharpScriptCompilationInfo(firstCompilation, null, null)) .VerifyDiagnostics(); AssertCompilationCorlib(secondCompilation); Assert.Same(firstCompilation.ObjectType, secondCompilation.ObjectType); Assert.Null(new CSharpScriptCompilationInfo(null, null, null) .WithPreviousScriptCompilation(firstCompilation) .ReturnTypeOpt); } [WorkItem(3719, "https://github.com/dotnet/roslyn/issues/3719")] [Fact] public void GetEntryPoint_Script() { var source = @"System.Console.WriteLine(1);"; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Script); compilation.VerifyDiagnostics(); var scriptMethod = compilation.GetMember<MethodSymbol>("Script.<Main>"); Assert.NotNull(scriptMethod); var method = compilation.GetEntryPoint(default(CancellationToken)); Assert.Equal(method, scriptMethod); var entryPoint = compilation.GetEntryPointAndDiagnostics(default(CancellationToken)); Assert.Equal(entryPoint.MethodSymbol, scriptMethod); } [Fact] public void GetEntryPoint_Script_MainIgnored() { var source = @" class A { static void Main() { } } "; var compilation = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (4,17): warning CS7022: The entry point of the program is global script code; ignoring 'A.Main()' entry point. // static void Main() { } Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("A.Main()").WithLocation(4, 17)); var scriptMethod = compilation.GetMember<MethodSymbol>("Script.<Main>"); Assert.NotNull(scriptMethod); var entryPoint = compilation.GetEntryPointAndDiagnostics(default(CancellationToken)); Assert.Equal(entryPoint.MethodSymbol, scriptMethod); entryPoint.Diagnostics.Verify( // (4,17): warning CS7022: The entry point of the program is global script code; ignoring 'A.Main()' entry point. // static void Main() { } Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("A.Main()").WithLocation(4, 17)); } [Fact] public void GetEntryPoint_Submission() { var source = @"1 + 1"; var compilation = CSharpCompilation.CreateScriptCompilation("sub", references: new[] { MscorlibRef }, syntaxTree: Parse(source, options: TestOptions.Script)); compilation.VerifyDiagnostics(); var scriptMethod = compilation.GetMember<MethodSymbol>("Script.<Factory>"); Assert.NotNull(scriptMethod); var method = compilation.GetEntryPoint(default(CancellationToken)); Assert.Equal(method, scriptMethod); var entryPoint = compilation.GetEntryPointAndDiagnostics(default(CancellationToken)); Assert.Equal(entryPoint.MethodSymbol, scriptMethod); entryPoint.Diagnostics.Verify(); } [Fact] public void GetEntryPoint_Submission_MainIgnored() { var source = @" class A { static void Main() { } } "; var compilation = CSharpCompilation.CreateScriptCompilation("sub", references: new[] { MscorlibRef }, syntaxTree: Parse(source, options: TestOptions.Script)); compilation.VerifyDiagnostics( // (4,17): warning CS7022: The entry point of the program is global script code; ignoring 'A.Main()' entry point. // static void Main() { } Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("A.Main()").WithLocation(4, 17)); Assert.True(compilation.IsSubmission); var scriptMethod = compilation.GetMember<MethodSymbol>("Script.<Factory>"); Assert.NotNull(scriptMethod); var entryPoint = compilation.GetEntryPointAndDiagnostics(default(CancellationToken)); Assert.Equal(entryPoint.MethodSymbol, scriptMethod); entryPoint.Diagnostics.Verify( // (4,17): warning CS7022: The entry point of the program is global script code; ignoring 'A.Main()' entry point. // static void Main() { } Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("A.Main()").WithLocation(4, 17)); } [Fact] public void GetEntryPoint_MainType() { var source = @" class A { static void Main() { } } class B { static void Main() { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithMainTypeName("B")); compilation.VerifyDiagnostics(); var mainMethod = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B").GetMember<MethodSymbol>("Main"); Assert.Equal(mainMethod, compilation.GetEntryPoint(default(CancellationToken))); var entryPointAndDiagnostics = compilation.GetEntryPointAndDiagnostics(default(CancellationToken)); Assert.Equal(mainMethod, entryPointAndDiagnostics.MethodSymbol); entryPointAndDiagnostics.Diagnostics.Verify(); } [Fact] public void CanReadAndWriteDefaultWin32Res() { var comp = CSharpCompilation.Create("Compilation"); var mft = new MemoryStream(new byte[] { 0, 1, 2, 3, }); var res = comp.CreateDefaultWin32Resources(true, false, mft, null); var list = comp.MakeWin32ResourceList(res, new DiagnosticBag()); Assert.Equal(2, list.Count); } [Fact, WorkItem(750437, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/750437")] public void ConflictingAliases() { var alias = Net451.System.WithAliases(new[] { "alias" }); var text = @"extern alias alias; using alias=alias; class myClass : alias::Uri { }"; var comp = CreateEmptyCompilation(text, references: new[] { MscorlibRef, alias }); Assert.Equal(2, comp.References.Count()); Assert.Equal("alias", comp.References.Last().Properties.Aliases.Single()); comp.VerifyDiagnostics( // (2,1): error CS1537: The using alias 'alias' appeared previously in this namespace // using alias=alias; Diagnostic(ErrorCode.ERR_DuplicateAlias, "using alias=alias;").WithArguments("alias"), // (3,17): error CS0104: 'alias' is an ambiguous reference between '<global namespace>' and '<global namespace>' // class myClass : alias::Uri Diagnostic(ErrorCode.ERR_AmbigContext, "alias").WithArguments("alias", "<global namespace>", "<global namespace>")); } [WorkItem(546088, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546088")] [Fact] public void CompilationDiagsIncorrectResult() { string source1 = @" using SysAttribute = System.Attribute; using MyAttribute = MyAttribute2Attribute; public class MyAttributeAttribute : SysAttribute {} public class MyAttribute2Attribute : SysAttribute {} [MyAttribute] public class TestClass { } "; string source2 = @""; // Ask for model diagnostics first. { var compilation = CreateCompilation(source: new string[] { source1, source2 }); var tree2 = compilation.SyntaxTrees[1]; //tree for empty file var model2 = compilation.GetSemanticModel(tree2); model2.GetDiagnostics().Verify(); // None, since the file is empty. compilation.GetDiagnostics().Verify( // (8,2): error CS1614: 'MyAttribute' is ambiguous between 'MyAttribute2Attribute' and 'MyAttributeAttribute'; use either '@MyAttribute' or 'MyAttributeAttribute' // [MyAttribute] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "MyAttribute").WithArguments("MyAttribute", "MyAttribute2Attribute", "MyAttributeAttribute")); } // Ask for compilation diagnostics first. { var compilation = CreateCompilation(source: new string[] { source1, source2 }); var tree2 = compilation.SyntaxTrees[1]; //tree for empty file var model2 = compilation.GetSemanticModel(tree2); compilation.GetDiagnostics().Verify( // (10,2): error CS1614: 'MyAttribute' is ambiguous between 'MyAttribute2Attribute' and 'MyAttributeAttribute'; use either '@MyAttribute' or 'MyAttributeAttribute' // [MyAttribute] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "MyAttribute").WithArguments("MyAttribute", "MyAttribute2Attribute", "MyAttributeAttribute")); model2.GetDiagnostics().Verify(); // None, since the file is empty. } } [Fact] public void ReferenceManagerReuse_WithOptions() { var c1 = CSharpCompilation.Create("c", options: TestOptions.ReleaseDll); var c2 = c1.WithOptions(TestOptions.ReleaseExe); Assert.True(c1.ReferenceManagerEquals(c2)); c2 = c1.WithOptions(TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsApplication)); Assert.True(c1.ReferenceManagerEquals(c2)); c2 = c1.WithOptions(TestOptions.ReleaseDll); Assert.True(c1.ReferenceManagerEquals(c2)); c2 = c1.WithOptions(TestOptions.ReleaseDll.WithOutputKind(OutputKind.NetModule)); Assert.False(c1.ReferenceManagerEquals(c2)); c1 = CSharpCompilation.Create("c", options: TestOptions.ReleaseModule); c2 = c1.WithOptions(TestOptions.ReleaseExe); Assert.False(c1.ReferenceManagerEquals(c2)); c2 = c1.WithOptions(TestOptions.ReleaseDll); Assert.False(c1.ReferenceManagerEquals(c2)); c2 = c1.WithOptions(TestOptions.CreateTestOptions(OutputKind.WindowsApplication, OptimizationLevel.Debug)); Assert.False(c1.ReferenceManagerEquals(c2)); c2 = c1.WithOptions(TestOptions.DebugModule.WithAllowUnsafe(true)); Assert.True(c1.ReferenceManagerEquals(c2)); } [Fact] public void ReferenceManagerReuse_WithMetadataReferenceResolver() { var c1 = CSharpCompilation.Create("c", options: TestOptions.ReleaseDll); var c2 = c1.WithOptions(TestOptions.ReleaseDll.WithMetadataReferenceResolver(new TestMetadataReferenceResolver())); Assert.False(c1.ReferenceManagerEquals(c2)); var c3 = c1.WithOptions(TestOptions.ReleaseDll.WithMetadataReferenceResolver(c1.Options.MetadataReferenceResolver)); Assert.True(c1.ReferenceManagerEquals(c3)); } [Fact] public void ReferenceManagerReuse_WithXmlFileResolver() { var c1 = CSharpCompilation.Create("c", options: TestOptions.ReleaseDll); var c2 = c1.WithOptions(TestOptions.ReleaseDll.WithXmlReferenceResolver(new XmlFileResolver(null))); Assert.False(c1.ReferenceManagerEquals(c2)); var c3 = c1.WithOptions(TestOptions.ReleaseDll.WithXmlReferenceResolver(c1.Options.XmlReferenceResolver)); Assert.True(c1.ReferenceManagerEquals(c3)); } [Fact] public void ReferenceManagerReuse_WithName() { var c1 = CSharpCompilation.Create("c1"); var c2 = c1.WithAssemblyName("c2"); Assert.False(c1.ReferenceManagerEquals(c2)); var c3 = c1.WithAssemblyName("c1"); Assert.True(c1.ReferenceManagerEquals(c3)); var c4 = c1.WithAssemblyName(null); Assert.False(c1.ReferenceManagerEquals(c4)); var c5 = c4.WithAssemblyName(null); Assert.True(c4.ReferenceManagerEquals(c5)); } [Fact] public void ReferenceManagerReuse_WithReferences() { var c1 = CSharpCompilation.Create("c1"); var c2 = c1.WithReferences(new[] { MscorlibRef }); Assert.False(c1.ReferenceManagerEquals(c2)); var c3 = c2.WithReferences(new[] { MscorlibRef, SystemCoreRef }); Assert.False(c3.ReferenceManagerEquals(c2)); c3 = c2.AddReferences(SystemCoreRef); Assert.False(c3.ReferenceManagerEquals(c2)); c3 = c2.RemoveAllReferences(); Assert.False(c3.ReferenceManagerEquals(c2)); c3 = c2.ReplaceReference(MscorlibRef, SystemCoreRef); Assert.False(c3.ReferenceManagerEquals(c2)); c3 = c2.RemoveReferences(MscorlibRef); Assert.False(c3.ReferenceManagerEquals(c2)); } [Fact] public void ReferenceManagerReuse_WithSyntaxTrees() { var ta = Parse("class C { }", options: TestOptions.Regular10); var tb = Parse(@" class C { }", options: TestOptions.Script); var tc = Parse(@" #r ""bar"" // error: #r in regular code class D { }", options: TestOptions.Regular10); var tr = Parse(@" #r ""goo"" class C { }", options: TestOptions.Script); var ts = Parse(@" #r ""bar"" class C { }", options: TestOptions.Script); var a = CSharpCompilation.Create("c", syntaxTrees: new[] { ta }); // add: var ab = a.AddSyntaxTrees(tb); Assert.True(a.ReferenceManagerEquals(ab)); var ac = a.AddSyntaxTrees(tc); Assert.True(a.ReferenceManagerEquals(ac)); var ar = a.AddSyntaxTrees(tr); Assert.False(a.ReferenceManagerEquals(ar)); var arc = ar.AddSyntaxTrees(tc); Assert.True(ar.ReferenceManagerEquals(arc)); // remove: var ar2 = arc.RemoveSyntaxTrees(tc); Assert.True(arc.ReferenceManagerEquals(ar2)); var c = arc.RemoveSyntaxTrees(ta, tr); Assert.False(arc.ReferenceManagerEquals(c)); var none1 = c.RemoveSyntaxTrees(tc); Assert.True(c.ReferenceManagerEquals(none1)); var none2 = arc.RemoveAllSyntaxTrees(); Assert.False(arc.ReferenceManagerEquals(none2)); var none3 = ac.RemoveAllSyntaxTrees(); Assert.True(ac.ReferenceManagerEquals(none3)); // replace: var asc = arc.ReplaceSyntaxTree(tr, ts); Assert.False(arc.ReferenceManagerEquals(asc)); var brc = arc.ReplaceSyntaxTree(ta, tb); Assert.True(arc.ReferenceManagerEquals(brc)); var abc = arc.ReplaceSyntaxTree(tr, tb); Assert.False(arc.ReferenceManagerEquals(abc)); var ars = arc.ReplaceSyntaxTree(tc, ts); Assert.False(arc.ReferenceManagerEquals(ars)); } [Fact] public void ReferenceManagerReuse_WithScriptCompilationInfo() { // Note: The following results would change if we optimized sharing more: https://github.com/dotnet/roslyn/issues/43397 var c1 = CSharpCompilation.CreateScriptCompilation("c1"); Assert.NotNull(c1.ScriptCompilationInfo); Assert.Null(c1.ScriptCompilationInfo.PreviousScriptCompilation); var c2 = c1.WithScriptCompilationInfo(null); Assert.Null(c2.ScriptCompilationInfo); Assert.True(c2.ReferenceManagerEquals(c1)); var c3 = c2.WithScriptCompilationInfo(new CSharpScriptCompilationInfo(previousCompilationOpt: null, returnType: typeof(int), globalsType: null)); Assert.NotNull(c3.ScriptCompilationInfo); Assert.Null(c3.ScriptCompilationInfo.PreviousScriptCompilation); Assert.True(c3.ReferenceManagerEquals(c2)); var c4 = c3.WithScriptCompilationInfo(null); Assert.Null(c4.ScriptCompilationInfo); Assert.True(c4.ReferenceManagerEquals(c3)); var c5 = c4.WithScriptCompilationInfo(new CSharpScriptCompilationInfo(previousCompilationOpt: c1, returnType: typeof(int), globalsType: null)); Assert.False(c5.ReferenceManagerEquals(c4)); var c6 = c5.WithScriptCompilationInfo(new CSharpScriptCompilationInfo(previousCompilationOpt: c1, returnType: typeof(bool), globalsType: null)); Assert.True(c6.ReferenceManagerEquals(c5)); var c7 = c6.WithScriptCompilationInfo(new CSharpScriptCompilationInfo(previousCompilationOpt: c2, returnType: typeof(bool), globalsType: null)); Assert.False(c7.ReferenceManagerEquals(c6)); var c8 = c7.WithScriptCompilationInfo(new CSharpScriptCompilationInfo(previousCompilationOpt: null, returnType: typeof(bool), globalsType: null)); Assert.False(c8.ReferenceManagerEquals(c7)); var c9 = c8.WithScriptCompilationInfo(null); Assert.True(c9.ReferenceManagerEquals(c8)); } private sealed class EvolvingTestReference : PortableExecutableReference { private readonly IEnumerator<Metadata> _metadataSequence; public int QueryCount; public EvolvingTestReference(IEnumerable<Metadata> metadataSequence) : base(MetadataReferenceProperties.Assembly) { _metadataSequence = metadataSequence.GetEnumerator(); } protected override DocumentationProvider CreateDocumentationProvider() { return DocumentationProvider.Default; } protected override Metadata GetMetadataImpl() { QueryCount++; _metadataSequence.MoveNext(); return _metadataSequence.Current; } protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties) { throw new NotImplementedException(); } } [ConditionalFact(typeof(NoUsedAssembliesValidation), typeof(NoIOperationValidation), Reason = "IOperation skip: Compilation changes over time, adds new errors")] public void MetadataConsistencyWhileEvolvingCompilation() { var md1 = AssemblyMetadata.CreateFromImage(CreateCompilation("public class C { }").EmitToArray()); var md2 = AssemblyMetadata.CreateFromImage(CreateCompilation("public class D { }").EmitToArray()); var reference = new EvolvingTestReference(new[] { md1, md2 }); var c1 = CreateEmptyCompilation("public class Main { public static C C; }", new[] { MscorlibRef, reference, reference }); var c2 = c1.WithAssemblyName("c2"); var c3 = c2.AddSyntaxTrees(Parse("public class Main2 { public static int a; }")); var c4 = c3.WithOptions(TestOptions.DebugModule); var c5 = c4.WithReferences(new[] { MscorlibRef, reference }); c3.VerifyDiagnostics(); c1.VerifyDiagnostics(); c4.VerifyDiagnostics(); c2.VerifyDiagnostics(); Assert.Equal(1, reference.QueryCount); c5.VerifyDiagnostics( // (1,36): error CS0246: The type or namespace name 'C' could not be found (are you missing a using directive or an assembly reference?) // public class Main2 { public static C C; } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C").WithArguments("C")); Assert.Equal(2, reference.QueryCount); } [Fact] public unsafe void LinkedNetmoduleMetadataMustProvideFullPEImage() { var netModule = TestResources.MetadataTests.NetModule01.ModuleCS00; PEHeaders h = new PEHeaders(new MemoryStream(netModule)); fixed (byte* ptr = &netModule[h.MetadataStartOffset]) { using (var mdModule = ModuleMetadata.CreateFromMetadata((IntPtr)ptr, h.MetadataSize)) { var c = CSharpCompilation.Create("Goo", references: new[] { MscorlibRef, mdModule.GetReference(display: "ModuleCS00") }, options: TestOptions.ReleaseDll); c.VerifyDiagnostics( // error CS7098: Linked netmodule metadata must provide a full PE image: 'ModuleCS00'. Diagnostic(ErrorCode.ERR_LinkedNetmoduleMetadataMustProvideFullPEImage).WithArguments("ModuleCS00").WithLocation(1, 1)); } } } [Fact] public void AppConfig1() { var references = new MetadataReference[] { Net451.mscorlib, Net451.System, TestReferences.NetFx.silverlight_v5_0_5_0.System }; var compilation = CreateEmptyCompilation( new[] { Parse("") }, references, options: TestOptions.ReleaseDll.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)); compilation.VerifyDiagnostics( // error CS1703: Multiple assemblies with equivalent identity have been imported: 'System.dll' and 'System.v5.0.5.0_silverlight.dll'. Remove one of the duplicate references. Diagnostic(ErrorCode.ERR_DuplicateImport).WithArguments("System.dll (net451)", "System.v5.0.5.0_silverlight.dll")); var appConfig = new MemoryStream(Encoding.UTF8.GetBytes( @"<?xml version=""1.0"" encoding=""utf-8"" ?> <configuration> <runtime> <assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1""> <supportPortability PKT=""7cec85d7bea7798e"" enable=""false""/> </assemblyBinding> </runtime> </configuration>")); var comparer = DesktopAssemblyIdentityComparer.LoadFromXml(appConfig); compilation = CreateEmptyCompilation( new[] { Parse("") }, references, options: TestOptions.ReleaseDll.WithAssemblyIdentityComparer(comparer)); compilation.VerifyDiagnostics(); } [Fact] public void AppConfig2() { // Create a dll with a reference to .NET system string libSource = @" using System.Runtime.Versioning; public class C { public static FrameworkName Goo() { return null; }}"; var libComp = CreateEmptyCompilation( libSource, references: new[] { MscorlibRef, Net451.System }, options: TestOptions.ReleaseDll); libComp.VerifyDiagnostics(); var refData = libComp.EmitToArray(); var mdRef = MetadataReference.CreateFromImage(refData); var references = new[] { Net451.mscorlib, Net451.System, TestReferences.NetFx.silverlight_v5_0_5_0.System, mdRef }; // Source references the type in the dll string src1 = @"class A { public static void Main(string[] args) { C.Goo(); } }"; var c1 = CreateEmptyCompilation( new[] { Parse(src1) }, references, options: TestOptions.ReleaseDll.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)); c1.VerifyDiagnostics( // error CS1703: Multiple assemblies with equivalent identity have been imported: 'System.dll' and 'System.v5.0.5.0_silverlight.dll'. Remove one of the duplicate references. Diagnostic(ErrorCode.ERR_DuplicateImport).WithArguments("System.dll (net451)", "System.v5.0.5.0_silverlight.dll"), // error CS7069: Reference to type 'System.Runtime.Versioning.FrameworkName' claims it is defined in 'System', but it could not be found Diagnostic(ErrorCode.ERR_MissingTypeInAssembly, "C.Goo").WithArguments( "System.Runtime.Versioning.FrameworkName", "System")); var appConfig = new MemoryStream(Encoding.UTF8.GetBytes( @"<?xml version=""1.0"" encoding=""utf-8"" ?> <configuration> <runtime> <assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1""> <supportPortability PKT=""7cec85d7bea7798e"" enable=""false""/> </assemblyBinding> </runtime> </configuration>")); var comparer = DesktopAssemblyIdentityComparer.LoadFromXml(appConfig); var src2 = @"class A { public static void Main(string[] args) { C.Goo(); } }"; var c2 = CreateEmptyCompilation( new[] { Parse(src2) }, references, options: TestOptions.ReleaseDll.WithAssemblyIdentityComparer(comparer)); c2.VerifyDiagnostics(); } [Fact] [WorkItem(797640, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797640")] public void GetMetadataReferenceAPITest() { var comp = CSharpCompilation.Create("Compilation"); var metadata = Net451.mscorlib; comp = comp.AddReferences(metadata); var assemblySmb = comp.GetReferencedAssemblySymbol(metadata); var reference = comp.GetMetadataReference(assemblySmb); Assert.NotNull(reference); var comp2 = CSharpCompilation.Create("Compilation"); comp2 = comp2.AddReferences(metadata); var reference2 = comp2.GetMetadataReference(assemblySmb); Assert.NotNull(reference2); } [Fact] [WorkItem(40466, "https://github.com/dotnet/roslyn/issues/40466")] public void GetMetadataReference_VisualBasicSymbols() { var comp = CreateCompilation(""); var vbComp = CreateVisualBasicCompilation("", referencedAssemblies: TargetFrameworkUtil.GetReferences(TargetFramework.Standard)); var assembly = (IAssemblySymbol)vbComp.GetBoundReferenceManager().GetReferencedAssemblies().First().Value; Assert.Null(comp.GetMetadataReference(assembly)); Assert.Null(comp.GetMetadataReference(vbComp.Assembly)); Assert.Null(comp.GetMetadataReference((IAssemblySymbol)null)); } [Fact] public void ConsistentParseOptions() { var tree1 = SyntaxFactory.ParseSyntaxTree("", CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6)); var tree2 = SyntaxFactory.ParseSyntaxTree("", CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6)); var tree3 = SyntaxFactory.ParseSyntaxTree("", CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5)); var assemblyName = GetUniqueName(); var compilationOptions = TestOptions.DebugDll; CSharpCompilation.Create(assemblyName, new[] { tree1, tree2 }, new[] { MscorlibRef }, compilationOptions); Assert.Throws<ArgumentException>(() => { CSharpCompilation.Create(assemblyName, new[] { tree1, tree3 }, new[] { MscorlibRef }, compilationOptions); }); } [Fact] public void SubmissionCompilation_Errors() { var genericParameter = typeof(List<>).GetGenericArguments()[0]; var open = typeof(Dictionary<,>).MakeGenericType(typeof(int), genericParameter); var ptr = typeof(int).MakePointerType(); var byref = typeof(int).MakeByRefType(); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", returnType: genericParameter)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", returnType: open)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", returnType: typeof(void))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", returnType: byref)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", globalsType: genericParameter)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", globalsType: open)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", globalsType: typeof(void))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", globalsType: typeof(int))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", globalsType: ptr)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", globalsType: byref)); var s0 = CSharpCompilation.CreateScriptCompilation("a0", globalsType: typeof(List<int>)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a1", previousScriptCompilation: s0, globalsType: typeof(List<bool>))); // invalid options: Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseExe)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.NetModule))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsRuntimeMetadata))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsRuntimeApplication))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsApplication))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithCryptoKeyContainer("goo"))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithCryptoKeyFile("goo.snk"))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithDelaySign(true))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithDelaySign(false))); } [Fact] public void HasSubmissionResult() { Assert.False(CSharpCompilation.CreateScriptCompilation("sub").HasSubmissionResult()); Assert.True(CreateSubmission("1", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.False(CreateSubmission("1;", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.False(CreateSubmission("void goo() { }", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.False(CreateSubmission("using System;", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.False(CreateSubmission("int i;", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.False(CreateSubmission("System.Console.WriteLine();", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.False(CreateSubmission("System.Console.WriteLine()", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.True(CreateSubmission("null", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.True(CreateSubmission("System.Console.WriteLine", parseOptions: TestOptions.Script).HasSubmissionResult()); } /// <summary> /// Previous submission has to have no errors. /// </summary> [Fact] public void PreviousSubmissionWithError() { var s0 = CreateSubmission("int a = \"x\";"); s0.VerifyDiagnostics( // (1,9): error CS0029: Cannot implicitly convert type 'string' to 'int' Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""x""").WithArguments("string", "int")); Assert.Throws<InvalidOperationException>(() => CreateSubmission("a + 1", previous: s0)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateArrayType_DefaultArgs() { var comp = (Compilation)CSharpCompilation.Create(""); var elementType = comp.GetSpecialType(SpecialType.System_Object); var arrayType = comp.CreateArrayTypeSymbol(elementType); Assert.Equal(1, arrayType.Rank); Assert.Equal(CodeAnalysis.NullableAnnotation.None, arrayType.ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, arrayType.ElementType.NullableAnnotation); Assert.Throws<ArgumentException>(() => comp.CreateArrayTypeSymbol(elementType, default)); Assert.Throws<ArgumentException>(() => comp.CreateArrayTypeSymbol(elementType, 0)); arrayType = comp.CreateArrayTypeSymbol(elementType, 1, default); Assert.Equal(1, arrayType.Rank); Assert.Equal(CodeAnalysis.NullableAnnotation.None, arrayType.ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, arrayType.ElementType.NullableAnnotation); Assert.Throws<ArgumentException>(() => comp.CreateArrayTypeSymbol(elementType, rank: default)); Assert.Throws<ArgumentException>(() => comp.CreateArrayTypeSymbol(elementType, rank: 0)); arrayType = comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: default); Assert.Equal(1, arrayType.Rank); Assert.Equal(CodeAnalysis.NullableAnnotation.None, arrayType.ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, arrayType.ElementType.NullableAnnotation); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateArrayType_ElementNullableAnnotation() { var comp = (Compilation)CSharpCompilation.Create(""); var elementType = comp.GetSpecialType(SpecialType.System_Object); Assert.Equal(CodeAnalysis.NullableAnnotation.None, comp.CreateArrayTypeSymbol(elementType).ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, comp.CreateArrayTypeSymbol(elementType).ElementType.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.None).ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.None).ElementType.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.None).ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.None).ElementType.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.NotAnnotated, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.NotAnnotated).ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.NotAnnotated, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.NotAnnotated).ElementType.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.Annotated).ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.Annotated).ElementType.NullableAnnotation); } [Fact] public void CreateAnonymousType_IncorrectLengths() { var compilation = CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)null), ImmutableArray.Create("m1", "m2"))); } [Fact] public void CreateAnonymousType_IncorrectLengths_IsReadOnly() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32), (ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray.Create("m1", "m2"), ImmutableArray.Create(true))); } [Fact] public void CreateAnonymousType_IncorrectLengths_Locations() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32), (ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray.Create("m1", "m2"), memberLocations: ImmutableArray.Create(Location.None))); } [Fact] public void CreateAnonymousType_WritableProperty() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32), (ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray.Create("m1", "m2"), ImmutableArray.Create(false, false))); } [Fact] public void CreateAnonymousType_NullLocations() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentNullException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32), (ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray.Create("m1", "m2"), memberLocations: ImmutableArray.Create(Location.None, null))); } [Fact] public void CreateAnonymousType_NullArgument1() { var compilation = CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentNullException>(() => compilation.CreateAnonymousTypeSymbol( default(ImmutableArray<ITypeSymbol>), ImmutableArray.Create("m1"))); } [Fact] public void CreateAnonymousType_NullArgument2() { var compilation = CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentNullException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)null), default(ImmutableArray<string>))); } [Fact] public void CreateAnonymousType_NullArgument3() { var compilation = CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentNullException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)null), ImmutableArray.Create("m1"))); } [Fact] public void CreateAnonymousType_NullArgument4() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentNullException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray.Create((string)null))); } [Fact] public void CreateAnonymousType1() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); var type = compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create<ITypeSymbol>(compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray.Create("m1")); Assert.True(type.IsAnonymousType); Assert.Equal(1, type.GetMembers().OfType<IPropertySymbol>().Count()); Assert.Equal("<anonymous type: int m1>", type.ToDisplayString()); Assert.All(type.GetMembers().OfType<IPropertySymbol>().Select(p => p.Locations.FirstOrDefault()), loc => Assert.Equal(loc, Location.None)); } [Fact] public void CreateAnonymousType_Locations() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); var tree = CSharpSyntaxTree.ParseText("class C { }"); var loc1 = Location.Create(tree, new TextSpan(0, 1)); var loc2 = Location.Create(tree, new TextSpan(1, 1)); var type = compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create<ITypeSymbol>(compilation.GetSpecialType(SpecialType.System_Int32), compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray.Create("m1", "m2"), memberLocations: ImmutableArray.Create(loc1, loc2)); Assert.True(type.IsAnonymousType); Assert.Equal(2, type.GetMembers().OfType<IPropertySymbol>().Count()); Assert.Equal(loc1, type.GetMembers("m1").Single().Locations.Single()); Assert.Equal(loc2, type.GetMembers("m2").Single().Locations.Single()); Assert.Equal("<anonymous type: int m1, int m2>", type.ToDisplayString()); } [Fact] public void CreateAnonymousType2() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); var type = compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create<ITypeSymbol>(compilation.GetSpecialType(SpecialType.System_Int32), compilation.GetSpecialType(SpecialType.System_Boolean)), ImmutableArray.Create("m1", "m2")); Assert.True(type.IsAnonymousType); Assert.Equal(2, type.GetMembers().OfType<IPropertySymbol>().Count()); Assert.Equal("<anonymous type: int m1, bool m2>", type.ToDisplayString()); Assert.All(type.GetMembers().OfType<IPropertySymbol>().Select(p => p.Locations.FirstOrDefault()), loc => Assert.Equal(loc, Location.None)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateAnonymousType_DefaultArgs() { var comp = (Compilation)CSharpCompilation.Create(""); var memberTypes = ImmutableArray.Create<ITypeSymbol>(comp.GetSpecialType(SpecialType.System_Object), comp.GetSpecialType(SpecialType.System_String)); var memberNames = ImmutableArray.Create("P", "Q"); var type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, default); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, default, default); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, default, default, default); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, memberIsReadOnly: default); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, memberLocations: default); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, memberNullableAnnotations: default); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateAnonymousType_MemberNullableAnnotations_Empty() { var comp = (Compilation)CSharpCompilation.Create(""); var type = comp.CreateAnonymousTypeSymbol(ImmutableArray<ITypeSymbol>.Empty, ImmutableArray<string>.Empty, memberNullableAnnotations: ImmutableArray<CodeAnalysis.NullableAnnotation>.Empty); Assert.Equal("<empty anonymous type>", type.ToTestDisplayString(includeNonNullable: true)); AssertEx.Equal(Array.Empty<CodeAnalysis.NullableAnnotation>(), GetAnonymousTypeNullableAnnotations(type)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateAnonymousType_MemberNullableAnnotations() { var comp = (Compilation)CSharpCompilation.Create(""); var memberTypes = ImmutableArray.Create<ITypeSymbol>(comp.GetSpecialType(SpecialType.System_Object), comp.GetSpecialType(SpecialType.System_String)); var memberNames = ImmutableArray.Create("P", "Q"); var type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.None, CodeAnalysis.NullableAnnotation.None }, GetAnonymousTypeNullableAnnotations(type)); Assert.Throws<ArgumentException>(() => comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, memberNullableAnnotations: ImmutableArray.Create(CodeAnalysis.NullableAnnotation.NotAnnotated))); type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, memberNullableAnnotations: ImmutableArray.Create(CodeAnalysis.NullableAnnotation.NotAnnotated, CodeAnalysis.NullableAnnotation.Annotated)); Assert.Equal("<anonymous type: System.Object! P, System.String? Q>", type.ToTestDisplayString(includeNonNullable: true)); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.NotAnnotated, CodeAnalysis.NullableAnnotation.Annotated }, GetAnonymousTypeNullableAnnotations(type)); } private static ImmutableArray<CodeAnalysis.NullableAnnotation> GetAnonymousTypeNullableAnnotations(ITypeSymbol type) { return type.GetMembers().OfType<IPropertySymbol>().SelectAsArray(p => { var result = p.Type.NullableAnnotation; Assert.Equal(result, p.NullableAnnotation); return result; }); } [Fact] [WorkItem(36046, "https://github.com/dotnet/roslyn/issues/36046")] public void ConstructTypeWithNullability() { var source = @"class Pair<T, U> { }"; var comp = (Compilation)CreateCompilation(source); var genericType = (INamedTypeSymbol)comp.GetMember("Pair"); var typeArguments = ImmutableArray.Create<ITypeSymbol>(comp.GetSpecialType(SpecialType.System_Object), comp.GetSpecialType(SpecialType.System_String)); Assert.Throws<ArgumentException>(() => genericType.Construct(default(ImmutableArray<ITypeSymbol>), default(ImmutableArray<CodeAnalysis.NullableAnnotation>))); Assert.Throws<ArgumentException>(() => genericType.Construct(typeArguments: default, typeArgumentNullableAnnotations: default)); var type = genericType.Construct(typeArguments, default); Assert.Equal("Pair<System.Object, System.String>", type.ToTestDisplayString(includeNonNullable: true)); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.None, CodeAnalysis.NullableAnnotation.None }, type.TypeArgumentNullableAnnotations); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.None, CodeAnalysis.NullableAnnotation.None }, type.TypeArgumentNullableAnnotations()); Assert.Throws<ArgumentException>(() => genericType.Construct(typeArguments, ImmutableArray<CodeAnalysis.NullableAnnotation>.Empty)); Assert.Throws<ArgumentException>(() => genericType.Construct(ImmutableArray.Create<ITypeSymbol>(null, null), default)); type = genericType.Construct(typeArguments, ImmutableArray.Create(CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.NotAnnotated)); Assert.Equal("Pair<System.Object?, System.String!>", type.ToTestDisplayString(includeNonNullable: true)); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.NotAnnotated }, type.TypeArgumentNullableAnnotations); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.NotAnnotated }, type.TypeArgumentNullableAnnotations()); // Type arguments from VB. comp = CreateVisualBasicCompilation(""); typeArguments = ImmutableArray.Create<ITypeSymbol>(comp.GetSpecialType(SpecialType.System_Object), comp.GetSpecialType(SpecialType.System_String)); Assert.Throws<ArgumentException>(() => genericType.Construct(typeArguments, default)); } [Fact] [WorkItem(37310, "https://github.com/dotnet/roslyn/issues/37310")] public void ConstructMethodWithNullability() { var source = @"class Program { static void M<T, U>() { } }"; var comp = (Compilation)CreateCompilation(source); var genericMethod = (IMethodSymbol)comp.GetMember("Program.M"); var typeArguments = ImmutableArray.Create<ITypeSymbol>(comp.GetSpecialType(SpecialType.System_Object), comp.GetSpecialType(SpecialType.System_String)); Assert.Throws<ArgumentException>(() => genericMethod.Construct(default(ImmutableArray<ITypeSymbol>), default(ImmutableArray<CodeAnalysis.NullableAnnotation>))); Assert.Throws<ArgumentException>(() => genericMethod.Construct(typeArguments: default, typeArgumentNullableAnnotations: default)); var type = genericMethod.Construct(typeArguments, default); Assert.Equal("void Program.M<System.Object, System.String>()", type.ToTestDisplayString(includeNonNullable: true)); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.None, CodeAnalysis.NullableAnnotation.None }, type.TypeArgumentNullableAnnotations); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.None, CodeAnalysis.NullableAnnotation.None }, type.TypeArgumentNullableAnnotations()); Assert.Throws<ArgumentException>(() => genericMethod.Construct(typeArguments, ImmutableArray<CodeAnalysis.NullableAnnotation>.Empty)); Assert.Throws<ArgumentException>(() => genericMethod.Construct(ImmutableArray.Create<ITypeSymbol>(null, null), default)); type = genericMethod.Construct(typeArguments, ImmutableArray.Create(CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.NotAnnotated)); Assert.Equal("void Program.M<System.Object?, System.String!>()", type.ToTestDisplayString(includeNonNullable: true)); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.NotAnnotated }, type.TypeArgumentNullableAnnotations); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.NotAnnotated }, type.TypeArgumentNullableAnnotations()); // Type arguments from VB. comp = CreateVisualBasicCompilation(""); typeArguments = ImmutableArray.Create<ITypeSymbol>(comp.GetSpecialType(SpecialType.System_Object), comp.GetSpecialType(SpecialType.System_String)); Assert.Throws<ArgumentException>(() => genericMethod.Construct(typeArguments, default)); } #region Script return values [ConditionalFact(typeof(DesktopOnly))] public void ReturnNullAsObject() { var script = CreateSubmission("return null;", returnType: typeof(object)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnStringAsObject() { var script = CreateSubmission("return \"¡Hola!\";", returnType: typeof(object)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnIntAsObject() { var script = CreateSubmission("return 42;", returnType: typeof(object)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void TrailingReturnVoidAsObject() { var script = CreateSubmission("return", returnType: typeof(object)); script.VerifyDiagnostics( // (1,7): error CS1733: Expected expression // return Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(1, 7), // (1,7): error CS1002: ; expected // return Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 7)); Assert.False(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnIntAsInt() { var script = CreateSubmission("return 42;", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnNullResultType() { // test that passing null is the same as passing typeof(object) var script = CreateSubmission("return 42;", returnType: null); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnNoSemicolon() { var script = CreateSubmission("return 42", returnType: typeof(uint)); script.VerifyDiagnostics( // (1,10): error CS1002: ; expected // return 42 Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 10)); Assert.False(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnAwait() { var script = CreateSubmission("return await System.Threading.Tasks.Task.FromResult(42);", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); script = CreateSubmission("return await System.Threading.Tasks.Task.FromResult(42);", returnType: typeof(Task<int>)); script.VerifyDiagnostics( // (1,8): error CS0029: Cannot implicitly convert type 'int' to 'System.Threading.Tasks.Task<int>' // return await System.Threading.Tasks.Task.FromResult(42); Diagnostic(ErrorCode.ERR_NoImplicitConv, "await System.Threading.Tasks.Task.FromResult(42)").WithArguments("int", "System.Threading.Tasks.Task<int>").WithLocation(1, 8)); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnTaskNoAwait() { var script = CreateSubmission("return System.Threading.Tasks.Task.FromResult(42);", returnType: typeof(int)); script.VerifyDiagnostics( // (1,8): error CS4016: Since this is an async method, the return expression must be of type 'int' rather than 'Task<int>' // return System.Threading.Tasks.Task.FromResult(42); Diagnostic(ErrorCode.ERR_BadAsyncReturnExpression, "System.Threading.Tasks.Task.FromResult(42)").WithArguments("int").WithLocation(1, 8)); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnInNestedScopes() { var script = CreateSubmission(@" bool condition = false; if (condition) { return 1; } else { return -1; }", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnInNestedScopeWithTrailingExpression() { var script = CreateSubmission(@" if (true) { return 1; } System.Console.WriteLine();", returnType: typeof(object)); script.VerifyDiagnostics( // (6,1): warning CS0162: Unreachable code detected // System.Console.WriteLine(); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(6, 1)); Assert.True(script.HasSubmissionResult()); script = CreateSubmission(@" if (true) { return 1; } System.Console.WriteLine()", returnType: typeof(object)); script.VerifyDiagnostics( // (6,1): warning CS0162: Unreachable code detected // System.Console.WriteLine(); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(6, 1)); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnInNestedScopeNoTrailingExpression() { var script = CreateSubmission(@" bool condition = false; if (condition) { return 1; } System.Console.WriteLine();", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnInNestedMethod() { var script = CreateSubmission(@" int TopMethod() { return 42; }", returnType: typeof(string)); script.VerifyDiagnostics(); Assert.False(script.HasSubmissionResult()); script = CreateSubmission(@" object TopMethod() { return new System.Exception(); } TopMethod().ToString()", returnType: typeof(string)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnInNestedLambda() { var script = CreateSubmission(@" System.Func<object> f = () => { return new System.Exception(); }; 42", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); script = CreateSubmission(@" System.Func<object> f = () => new System.Exception(); 42", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnInNestedAnonymousMethod() { var script = CreateSubmission(@" System.Func<object> f = delegate () { return new System.Exception(); }; 42", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void LoadedFileWithWrongReturnType() { var resolver = TestSourceReferenceResolver.Create( KeyValuePairUtil.Create("a.csx", "return \"Who returns a string?\";")); var script = CreateSubmission(@" #load ""a.csx"" 42", returnType: typeof(int), options: TestOptions.DebugDll.WithSourceReferenceResolver(resolver)); script.VerifyDiagnostics( // a.csx(1,8): error CS0029: Cannot implicitly convert type 'string' to 'int' // return "Who returns a string?" Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""Who returns a string?""").WithArguments("string", "int").WithLocation(1, 8), // (3,1): warning CS0162: Unreachable code detected // 42 Diagnostic(ErrorCode.WRN_UnreachableCode, "42").WithLocation(3, 1)); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnVoidInNestedMethodOrLambda() { var script = CreateSubmission(@" void M1() { return; } System.Action a = () => { return; }; 42", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); var compilation = CreateCompilationWithMscorlib45(@" void M1() { return; } System.Action a = () => { return; }; 42", parseOptions: TestOptions.Script); compilation.VerifyDiagnostics(); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Reflection.PortableExecutable; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using VB = Microsoft.CodeAnalysis.VisualBasic; using KeyValuePairUtil = Roslyn.Utilities.KeyValuePairUtil; using System.Security.Cryptography; using static Roslyn.Test.Utilities.TestHelpers; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class CompilationAPITests : CSharpTestBase { private CSharpCompilationOptions WithDiagnosticOptions( SyntaxTree tree, params (string, ReportDiagnostic)[] options) => TestOptions.DebugDll.WithSyntaxTreeOptionsProvider(new TestSyntaxTreeOptionsProvider(tree, options)); [Fact] public void TreeDiagnosticOptionsDoNotAffectTreeDiagnostics() { #pragma warning disable CS0618 // This test is intentionally calling the obsolete method to assert the diagnosticOptions input is now ignored var tree = SyntaxFactory.ParseSyntaxTree("class C { long _f = 0l;}", options: null, path: "", encoding: null, diagnosticOptions: CreateImmutableDictionary(("CS0078", ReportDiagnostic.Suppress)), cancellationToken: default); tree.GetDiagnostics().Verify( // (1,22): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // class C { long _f = 0l;} Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(1, 22)); #pragma warning restore CS0618 } [Fact] public void PerTreeVsGlobalSuppress() { var tree = SyntaxFactory.ParseSyntaxTree("class C { long _f = 0l;}"); var options = TestOptions.DebugDll .WithGeneralDiagnosticOption(ReportDiagnostic.Suppress); var comp = CreateCompilation(tree, options: options); comp.VerifyDiagnostics(); options = options.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider((tree, new[] { ("CS0078", ReportDiagnostic.Warn) }))); comp = CreateCompilation(tree, options: options); // Syntax tree diagnostic options override global settting comp.VerifyDiagnostics( // (1,22): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // class C { long _f = 0l;} Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(1, 22)); } [Fact] public void PerTreeDiagnosticOptionsParseWarnings() { var tree = SyntaxFactory.ParseSyntaxTree("class C { long _f = 0l;}"); var comp = CreateCompilation(tree); comp.VerifyDiagnostics( // (1,22): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // class C { long _f = 0l;} Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(1, 22), // (1,16): warning CS0414: The field 'C._f' is assigned but its value is never used // class C { long _f = 0l;} Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(1, 16)); var options = WithDiagnosticOptions(tree, ("CS0078", ReportDiagnostic.Suppress)); comp = CreateCompilation(tree, options: options); comp.VerifyDiagnostics( // (1,16): warning CS0414: The field 'C._f' is assigned but its value is never used // class C { long _f = 0l;} Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(1, 16)); } [Fact] public void PerTreeDiagnosticOptionsVsPragma() { var tree = SyntaxFactory.ParseSyntaxTree(@" class C { #pragma warning disable CS0078 long _f = 0l; #pragma warning restore CS0078 }"); tree.GetDiagnostics().Verify( // (4,12): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // long _f = 0l; Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(4, 12)); var comp = CreateCompilation(tree); comp.VerifyDiagnostics( // (4,6): warning CS0414: The field 'C._f' is assigned but its value is never used // long _f = 0l; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(4, 6)); var options = WithDiagnosticOptions(tree, ("CS0078", ReportDiagnostic.Error)); comp = CreateCompilation(tree, options: options); // Pragma should have precedence over per-tree options comp.VerifyDiagnostics( // (4,6): warning CS0414: The field 'C._f' is assigned but its value is never used // long _f = 0l; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(4, 6)); } [Fact] public void PerTreeDiagnosticOptionsVsSpecificOptions() { var tree = SyntaxFactory.ParseSyntaxTree("class C { long _f = 0l; }"); var options = WithDiagnosticOptions(tree, ("CS0078", ReportDiagnostic.Suppress)); var comp = CreateCompilation(tree, options: options); comp.VerifyDiagnostics( // (1,16): warning CS0414: The field 'C._f' is assigned but its value is never used // class C { long _f = 0l; } Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(1, 16) ); options = options.WithSpecificDiagnosticOptions( CreateImmutableDictionary(("CS0078", ReportDiagnostic.Error))); var comp2 = CreateCompilation(tree, options: options); // Specific diagnostic options have precedence over per-tree options comp2.VerifyDiagnostics( // (1,16): warning CS0414: The field 'C._f' is assigned but its value is never used // class C { long _f = 0l; } Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(1, 16), // (1,22): error CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // class C { long _f = 0l; } Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(1, 22).WithWarningAsError(true)); } [Fact] public void DifferentDiagnosticOptionsForTrees() { var tree = SyntaxFactory.ParseSyntaxTree(@" class C { long _f = 0l; }"); var newTree = SyntaxFactory.ParseSyntaxTree(@" class D { long _f = 0l; }"); var options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider( (tree, new[] { ("CS0078", ReportDiagnostic.Suppress) }), (newTree, new[] { ("CS0078", ReportDiagnostic.Error) }) ) ); var comp = CreateCompilation(new[] { tree, newTree }, options: options); comp.VerifyDiagnostics( // (1,23): error CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // class D { long _f = 0l; } Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(1, 23).WithWarningAsError(true), // (1,17): warning CS0414: The field 'D._f' is assigned but its value is never used // class D { long _f = 0l; } Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("D._f").WithLocation(1, 17), // (1,17): warning CS0414: The field 'C._f' is assigned but its value is never used // class C { long _f = 0l; } Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(1, 17) ); } [Fact] public void TreeOptionsComparerRespected() { var tree = SyntaxFactory.ParseSyntaxTree(@" class C { long _f = 0l; }"); // Default options have case insensitivity var options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider((tree, new[] { ("cs0078", ReportDiagnostic.Suppress) })) ); CreateCompilation(tree, options: options).VerifyDiagnostics( // (1,17): warning CS0414: The field 'C._f' is assigned but its value is never used // class C { long _f = 0l; } Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(1, 17) ); options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider( StringComparer.Ordinal, globalOption: default, (tree, new[] { ("cs0078", ReportDiagnostic.Suppress) })) ); CreateCompilation(tree, options: options).VerifyDiagnostics( // (1,23): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // class C { long _f = 0l; } Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(1, 23), // (1,17): warning CS0414: The field 'C._f' is assigned but its value is never used // class C { long _f = 0l; } Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(1, 17) ); } [Fact] public void WarningLevelRespectedForLexerWarnings() { var source = @"public class C { public long Field = 0l; }"; CreateCompilation(source).VerifyDiagnostics( // (1,39): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // public class C { public long Field = 0l; } Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(1, 39) ); CreateCompilation(source, options: TestOptions.ReleaseDll.WithWarningLevel(0)).VerifyDiagnostics( ); } [WorkItem(8360, "https://github.com/dotnet/roslyn/issues/8360")] [WorkItem(9153, "https://github.com/dotnet/roslyn/issues/9153")] [Fact] public void PublicSignWithRelativeKeyPath() { var options = TestOptions.DebugDll .WithPublicSign(true).WithCryptoKeyFile("test.snk"); var comp = CSharpCompilation.Create("test", options: options); comp.VerifyDiagnostics( // error CS7104: Option 'CryptoKeyFile' must be an absolute path. Diagnostic(ErrorCode.ERR_OptionMustBeAbsolutePath).WithArguments("CryptoKeyFile").WithLocation(1, 1), // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1) ); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void PublicSignWithEmptyKeyPath() { CreateCompilation("", options: TestOptions.ReleaseDll.WithPublicSign(true).WithCryptoKeyFile("")).VerifyDiagnostics( // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1)); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void PublicSignWithEmptyKeyPath2() { CreateCompilation("", options: TestOptions.ReleaseDll.WithPublicSign(true).WithCryptoKeyFile("\"\"")).VerifyDiagnostics( // error CS8106: Option 'CryptoKeyFile' must be an absolute path. Diagnostic(ErrorCode.ERR_OptionMustBeAbsolutePath).WithArguments("CryptoKeyFile").WithLocation(1, 1), // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1)); } [Fact] [WorkItem(233669, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=233669")] public void CompilationName() { // report an error, rather then silently ignoring the directory // (see cli partition II 22.30) CSharpCompilation.Create(@"C:/goo/Test.exe").VerifyEmitDiagnostics( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1), // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1), // error CS5001: Program does not contain a static 'Main' method suitable for an entry point Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1) ); CSharpCompilation.Create(@"C:\goo\Test.exe").GetDeclarationDiagnostics().Verify( // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); var compilationOptions = TestOptions.DebugDll.WithWarningLevel(0); CSharpCompilation.Create(@"\goo/Test.exe", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); CSharpCompilation.Create(@"C:Test.exe", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); CSharpCompilation.Create(@"Te\0st.exe", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); CSharpCompilation.Create(@" \t ", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name cannot start with whitespace. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name cannot start with whitespace.").WithLocation(1, 1) ); CSharpCompilation.Create(@"\uD800", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); CSharpCompilation.Create(@"", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name cannot be empty. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name cannot be empty.").WithLocation(1, 1) ); CSharpCompilation.Create(@" a", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name cannot start with whitespace. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name cannot start with whitespace.").WithLocation(1, 1) ); CSharpCompilation.Create(@"\u2000a", options: compilationOptions).VerifyEmitDiagnostics( // U+20700 is whitespace // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); CSharpCompilation.Create("..\\..\\RelativePath", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); // other characters than directory and volume separators are ok: CSharpCompilation.Create(@";,*?<>#!@&", options: compilationOptions).VerifyEmitDiagnostics(); CSharpCompilation.Create("goo", options: compilationOptions).VerifyEmitDiagnostics(); CSharpCompilation.Create(".goo", options: compilationOptions).VerifyEmitDiagnostics(); CSharpCompilation.Create("goo ", options: compilationOptions).VerifyEmitDiagnostics(); // can end with whitespace CSharpCompilation.Create("....", options: compilationOptions).VerifyEmitDiagnostics(); CSharpCompilation.Create(null, options: compilationOptions).VerifyEmitDiagnostics(); } [Fact] public void CreateAPITest() { var listSyntaxTree = new List<SyntaxTree>(); var listRef = new List<MetadataReference>(); var s1 = @"using Goo; namespace A.B { class C { class D { class E { } } } class G<T> { class Q<S1,S2> { } } class G<T1,T2> { } }"; SyntaxTree t1 = SyntaxFactory.ParseSyntaxTree(s1); listSyntaxTree.Add(t1); // System.dll listRef.Add(Net451.System.WithEmbedInteropTypes(true)); var ops = TestOptions.ReleaseExe; // Create Compilation with Option is not null var comp = CSharpCompilation.Create("Compilation", listSyntaxTree, listRef, ops); Assert.Equal(ops, comp.Options); Assert.NotEqual(default, comp.SyntaxTrees); Assert.NotNull(comp.References); Assert.Equal(1, comp.SyntaxTrees.Length); Assert.Equal(1, comp.ExternalReferences.Length); var ref1 = comp.ExternalReferences[0]; Assert.True(ref1.Properties.EmbedInteropTypes); Assert.True(ref1.Properties.Aliases.IsEmpty); // Create Compilation with PreProcessorSymbols of Option is empty var ops1 = TestOptions.DebugExe; // Create Compilation with Assembly name contains invalid char var asmname = "ÃÃâ€Â"; comp = CSharpCompilation.Create(asmname, listSyntaxTree, listRef, ops); var comp1 = CSharpCompilation.Create(asmname, listSyntaxTree, listRef, null); } [Fact] public void EmitToNonWritableStreams() { var peStream = new TestStream(canRead: false, canSeek: false, canWrite: false); var pdbStream = new TestStream(canRead: false, canSeek: false, canWrite: false); var c = CSharpCompilation.Create("a", new[] { SyntaxFactory.ParseSyntaxTree("class C { static void Main() {} }") }, new[] { MscorlibRef }); Assert.Throws<ArgumentException>(() => c.Emit(peStream)); Assert.Throws<ArgumentException>(() => c.Emit(new MemoryStream(), pdbStream)); } [Fact] public void EmitOptionsDiagnostics() { var c = CreateCompilation("class C {}"); var stream = new MemoryStream(); var options = new EmitOptions( debugInformationFormat: (DebugInformationFormat)(-1), outputNameOverride: " ", fileAlignment: 513, subsystemVersion: SubsystemVersion.Create(1000000, -1000000), pdbChecksumAlgorithm: new HashAlgorithmName("invalid hash algorithm name")); EmitResult result = c.Emit(stream, options: options); result.Diagnostics.Verify( // error CS2042: Invalid debug information format: -1 Diagnostic(ErrorCode.ERR_InvalidDebugInformationFormat).WithArguments("-1").WithLocation(1, 1), // error CS2041: Invalid output name: Name cannot start with whitespace. Diagnostic(ErrorCode.ERR_InvalidOutputName).WithArguments("Name cannot start with whitespace.").WithLocation(1, 1), // error CS2024: Invalid file section alignment '513' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("513").WithLocation(1, 1), // error CS1773: Invalid version 1000000.-1000000 for /subsystemversion. The version must be 6.02 or greater for ARM or AppContainerExe, and 4.00 or greater otherwise Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("1000000.-1000000").WithLocation(1, 1), // error CS8113: Invalid hash algorithm name: 'invalid hash algorithm name' Diagnostic(ErrorCode.ERR_InvalidHashAlgorithmName).WithArguments("invalid hash algorithm name").WithLocation(1, 1)); Assert.False(result.Success); } [Fact] public void EmitOptions_PdbChecksumAndDeterminism() { var options = new EmitOptions(pdbChecksumAlgorithm: default(HashAlgorithmName)); var diagnosticBag = new DiagnosticBag(); options.ValidateOptions(diagnosticBag, MessageProvider.Instance, isDeterministic: true); diagnosticBag.Verify( // error CS8113: Invalid hash algorithm name: '' Diagnostic(ErrorCode.ERR_InvalidHashAlgorithmName).WithArguments("")); diagnosticBag.Clear(); options.ValidateOptions(diagnosticBag, MessageProvider.Instance, isDeterministic: false); diagnosticBag.Verify(); } [Fact] public void Emit_BadArgs() { var comp = CSharpCompilation.Create("Compilation", options: TestOptions.ReleaseDll); Assert.Throws<ArgumentNullException>("peStream", () => comp.Emit(peStream: null)); Assert.Throws<ArgumentException>("peStream", () => comp.Emit(peStream: new TestStream(canRead: true, canWrite: false, canSeek: true))); Assert.Throws<ArgumentException>("pdbStream", () => comp.Emit(peStream: new MemoryStream(), pdbStream: new TestStream(canRead: true, canWrite: false, canSeek: true))); Assert.Throws<ArgumentException>("pdbStream", () => comp.Emit(peStream: new MemoryStream(), pdbStream: new MemoryStream(), options: EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.Embedded))); Assert.Throws<ArgumentException>("sourceLinkStream", () => comp.Emit( peStream: new MemoryStream(), pdbStream: new MemoryStream(), options: EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), sourceLinkStream: new TestStream(canRead: false, canWrite: true, canSeek: true))); Assert.Throws<ArgumentException>("embeddedTexts", () => comp.Emit( peStream: new MemoryStream(), pdbStream: null, options: null, embeddedTexts: new[] { EmbeddedText.FromStream("_", new MemoryStream()) })); Assert.Throws<ArgumentException>("embeddedTexts", () => comp.Emit( peStream: new MemoryStream(), pdbStream: null, options: EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), embeddedTexts: new[] { EmbeddedText.FromStream("_", new MemoryStream()) })); Assert.Throws<ArgumentException>("win32Resources", () => comp.Emit( peStream: new MemoryStream(), win32Resources: new TestStream(canRead: true, canWrite: false, canSeek: false))); Assert.Throws<ArgumentException>("win32Resources", () => comp.Emit( peStream: new MemoryStream(), win32Resources: new TestStream(canRead: false, canWrite: false, canSeek: true))); // we don't report an error when we can't write to the XML doc stream: Assert.True(comp.Emit( peStream: new MemoryStream(), pdbStream: new MemoryStream(), xmlDocumentationStream: new TestStream(canRead: true, canWrite: false, canSeek: true)).Success); } [Fact] public void ReferenceAPITest() { var opt = TestOptions.DebugExe; // Create Compilation takes two args var comp = CSharpCompilation.Create("Compilation", options: TestOptions.DebugExe); var ref1 = Net451.mscorlib; var ref2 = Net451.System; var ref3 = new TestMetadataReference(fullPath: @"c:\xml.bms"); var ref4 = new TestMetadataReference(fullPath: @"c:\aaa.dll"); // Add a new empty item comp = comp.AddReferences(Enumerable.Empty<MetadataReference>()); Assert.Equal(0, comp.ExternalReferences.Length); // Add a new valid item comp = comp.AddReferences(ref1); var assemblySmb = comp.GetReferencedAssemblySymbol(ref1); Assert.NotNull(assemblySmb); Assert.Equal("mscorlib", assemblySmb.Name, StringComparer.OrdinalIgnoreCase); Assert.Equal(1, comp.ExternalReferences.Length); Assert.Equal(MetadataImageKind.Assembly, comp.ExternalReferences[0].Properties.Kind); Assert.Equal(ref1, comp.ExternalReferences[0]); // Replace an existing item with another valid item comp = comp.ReplaceReference(ref1, ref2); Assert.Equal(1, comp.ExternalReferences.Length); Assert.Equal(MetadataImageKind.Assembly, comp.ExternalReferences[0].Properties.Kind); Assert.Equal(ref2, comp.ExternalReferences[0]); // Remove an existing item comp = comp.RemoveReferences(ref2); Assert.Equal(0, comp.ExternalReferences.Length); // Overload with Hashset var hs = new HashSet<MetadataReference> { ref1, ref2, ref3 }; var compCollection = CSharpCompilation.Create("Compilation", references: hs, options: opt); compCollection = compCollection.AddReferences(ref1, ref2, ref3, ref4).RemoveReferences(hs); Assert.Equal(1, compCollection.ExternalReferences.Length); compCollection = compCollection.AddReferences(hs).RemoveReferences(ref1, ref2, ref3, ref4); Assert.Equal(0, compCollection.ExternalReferences.Length); // Overload with Collection var col = new Collection<MetadataReference> { ref1, ref2, ref3 }; compCollection = CSharpCompilation.Create("Compilation", references: col, options: opt); compCollection = compCollection.AddReferences(col).RemoveReferences(ref1, ref2, ref3); Assert.Equal(0, compCollection.ExternalReferences.Length); compCollection = compCollection.AddReferences(ref1, ref2, ref3).RemoveReferences(col); Assert.Equal(0, comp.ExternalReferences.Length); // Overload with ConcurrentStack var stack = new ConcurrentStack<MetadataReference> { }; stack.Push(ref1); stack.Push(ref2); stack.Push(ref3); compCollection = CSharpCompilation.Create("Compilation", references: stack, options: opt); compCollection = compCollection.AddReferences(stack).RemoveReferences(ref1, ref3, ref2); Assert.Equal(0, compCollection.ExternalReferences.Length); compCollection = compCollection.AddReferences(ref2, ref1, ref3).RemoveReferences(stack); Assert.Equal(0, compCollection.ExternalReferences.Length); // Overload with ConcurrentQueue var queue = new ConcurrentQueue<MetadataReference> { }; queue.Enqueue(ref1); queue.Enqueue(ref2); queue.Enqueue(ref3); compCollection = CSharpCompilation.Create("Compilation", references: queue, options: opt); compCollection = compCollection.AddReferences(queue).RemoveReferences(ref3, ref2, ref1); Assert.Equal(0, compCollection.ExternalReferences.Length); compCollection = compCollection.AddReferences(ref2, ref1, ref3).RemoveReferences(queue); Assert.Equal(0, compCollection.ExternalReferences.Length); } [Fact] public void ReferenceDirectiveTests() { var t1 = Parse(@" #r ""a.dll"" #r ""a.dll"" ", filename: "1.csx", options: TestOptions.Script); var rd1 = t1.GetRoot().GetDirectives().Cast<ReferenceDirectiveTriviaSyntax>().ToArray(); Assert.Equal(2, rd1.Length); var t2 = Parse(@" #r ""a.dll"" #r ""b.dll"" ", options: TestOptions.Script); var rd2 = t2.GetRoot().GetDirectives().Cast<ReferenceDirectiveTriviaSyntax>().ToArray(); Assert.Equal(2, rd2.Length); var t3 = Parse(@" #r ""a.dll"" ", filename: "1.csx", options: TestOptions.Script); var rd3 = t3.GetRoot().GetDirectives().Cast<ReferenceDirectiveTriviaSyntax>().ToArray(); Assert.Equal(1, rd3.Length); var t4 = Parse(@" #r ""a.dll"" ", filename: "4.csx", options: TestOptions.Script); var rd4 = t4.GetRoot().GetDirectives().Cast<ReferenceDirectiveTriviaSyntax>().ToArray(); Assert.Equal(1, rd4.Length); var c = CreateCompilationWithMscorlib45(new[] { t1, t2 }, options: TestOptions.ReleaseDll.WithMetadataReferenceResolver( new TestMetadataReferenceResolver(files: new Dictionary<string, PortableExecutableReference>() { { @"a.dll", Net451.MicrosoftCSharp }, { @"b.dll", Net451.MicrosoftVisualBasic }, }))); c.VerifyDiagnostics(); // same containing script file name and directive string Assert.Same(Net451.MicrosoftCSharp, c.GetDirectiveReference(rd1[0])); Assert.Same(Net451.MicrosoftCSharp, c.GetDirectiveReference(rd1[1])); Assert.Same(Net451.MicrosoftCSharp, c.GetDirectiveReference(rd2[0])); Assert.Same(Net451.MicrosoftVisualBasic, c.GetDirectiveReference(rd2[1])); Assert.Same(Net451.MicrosoftCSharp, c.GetDirectiveReference(rd3[0])); // different script name or directive string: Assert.Null(c.GetDirectiveReference(rd4[0])); } [Fact, WorkItem(530131, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530131")] public void MetadataReferenceWithInvalidAlias() { var refcomp = CSharpCompilation.Create("DLL", options: TestOptions.ReleaseDll, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree("public class C {}") }, references: new MetadataReference[] { MscorlibRef }); var mtref = refcomp.EmitToImageReference(aliases: ImmutableArray.Create("a", "Alias(*#$@^%*&)")); // not use exported type var comp = CSharpCompilation.Create("APP", options: TestOptions.ReleaseDll, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree( @"class D {}" ) }, references: new MetadataReference[] { MscorlibRef, mtref } ); Assert.Empty(comp.GetDiagnostics()); // use exported type with partial alias comp = CSharpCompilation.Create("APP1", options: TestOptions.ReleaseDll, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree( @"extern alias Alias; class D : Alias::C {}" ) }, references: new MetadataReference[] { MscorlibRef, mtref } ); var errs = comp.GetDiagnostics(); // error CS0430: The extern alias 'Alias' was not specified in a /reference option Assert.Equal(430, errs.FirstOrDefault().Code); // use exported type with invalid alias comp = CSharpCompilation.Create("APP2", options: TestOptions.ReleaseExe, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree( "extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {}", options: TestOptions.Regular9) }, references: new MetadataReference[] { MscorlibRef, mtref } ); comp.VerifyDiagnostics( // (1,21): error CS1040: Preprocessor directives must appear as the first non-whitespace character on a line // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_BadDirectivePlacement, "#").WithLocation(1, 21), // (1,61): error CS1026: ) expected // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(1, 61), // (1,61): error CS1002: ; expected // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 61), // (1,14): error CS8112: Local function 'Alias()' must declare a body because it is not marked 'static extern'. // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "Alias").WithArguments("Alias()").WithLocation(1, 14), // (1,8): error CS0246: The type or namespace name 'alias' could not be found (are you missing a using directive or an assembly reference?) // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias").WithArguments("alias").WithLocation(1, 8), // (1,14): warning CS0626: Method, operator, or accessor 'Alias()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "Alias").WithArguments("Alias()").WithLocation(1, 14), // (1,14): warning CS8321: The local function 'Alias' is declared but never used // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Alias").WithArguments("Alias").WithLocation(1, 14) ); } [Fact, WorkItem(530131, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530131")] public void MetadataReferenceWithInvalidAliasWithCSharp6() { var refcomp = CSharpCompilation.Create("DLL", options: TestOptions.ReleaseDll, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree("public class C {}", options: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)) }, references: new MetadataReference[] { MscorlibRef }); var mtref = refcomp.EmitToImageReference(aliases: ImmutableArray.Create("a", "Alias(*#$@^%*&)")); // not use exported type var comp = CSharpCompilation.Create("APP", options: TestOptions.ReleaseDll, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree( @"class D {}", options: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)) }, references: new MetadataReference[] { MscorlibRef, mtref } ); Assert.Empty(comp.GetDiagnostics()); // use exported type with partial alias comp = CSharpCompilation.Create("APP1", options: TestOptions.ReleaseDll, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree( @"extern alias Alias; class D : Alias::C {}", options: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)) }, references: new MetadataReference[] { MscorlibRef, mtref } ); var errs = comp.GetDiagnostics(); // error CS0430: The extern alias 'Alias' was not specified in a /reference option Assert.Equal(430, errs.FirstOrDefault().Code); // use exported type with invalid alias comp = CSharpCompilation.Create("APP2", options: TestOptions.ReleaseExe, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree( "extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {}", options: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)) }, references: new MetadataReference[] { MscorlibRef, mtref } ); comp.VerifyDiagnostics( // (1,1): error CS8059: Feature 'top-level statements' is not available in C# 6. Please use language version 9.0 or greater. // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {}").WithArguments("top-level statements", "9.0").WithLocation(1, 1), // (1,1): error CS8059: Feature 'extern local functions' is not available in C# 6. Please use language version 9.0 or greater. // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "extern").WithArguments("extern local functions", "9.0").WithLocation(1, 1), // (1,14): error CS8059: Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater. // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "Alias").WithArguments("local functions", "7.0").WithLocation(1, 14), // (1,21): error CS1040: Preprocessor directives must appear as the first non-whitespace character on a line // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_BadDirectivePlacement, "#").WithLocation(1, 21), // (1,61): error CS1026: ) expected // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(1, 61), // (1,61): error CS1002: ; expected // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 61), // (1,14): error CS8112: Local function 'Alias()' must declare a body because it is not marked 'static extern'. // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "Alias").WithArguments("Alias()").WithLocation(1, 14), // (1,8): error CS0246: The type or namespace name 'alias' could not be found (are you missing a using directive or an assembly reference?) // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias").WithArguments("alias").WithLocation(1, 8), // (1,14): warning CS0626: Method, operator, or accessor 'Alias()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "Alias").WithArguments("Alias()").WithLocation(1, 14), // (1,14): warning CS8321: The local function 'Alias' is declared but never used // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Alias").WithArguments("Alias").WithLocation(1, 14) ); } [Fact] public void SyntreeAPITest() { var s1 = "namespace System.Linq {}"; var s2 = @" namespace NA.NB { partial class C<T> { public partial class D { intttt F; } } class C { } } "; var s3 = @"int x;"; var s4 = @"Imports System "; var s5 = @" class D { public static int Goo() { long l = 25l; return 0; } } "; SyntaxTree t1 = SyntaxFactory.ParseSyntaxTree(s1); SyntaxTree withErrorTree = SyntaxFactory.ParseSyntaxTree(s2); SyntaxTree withErrorTree1 = SyntaxFactory.ParseSyntaxTree(s3); SyntaxTree withErrorTreeVB = SyntaxFactory.ParseSyntaxTree(s4); SyntaxTree withExpressionRootTree = SyntaxFactory.ParseExpression(s3).SyntaxTree; var withWarning = SyntaxFactory.ParseSyntaxTree(s5); // Create compilation takes three args var comp = CSharpCompilation.Create("Compilation", syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree(s1) }, options: TestOptions.ReleaseDll); comp = comp.AddSyntaxTrees(t1, withErrorTree, withErrorTree1, withErrorTreeVB); Assert.Equal(5, comp.SyntaxTrees.Length); comp = comp.RemoveSyntaxTrees(t1, withErrorTree, withErrorTree1, withErrorTreeVB); Assert.Equal(1, comp.SyntaxTrees.Length); // Add a new empty item comp = comp.AddSyntaxTrees(Enumerable.Empty<SyntaxTree>()); Assert.Equal(1, comp.SyntaxTrees.Length); // Add a new valid item comp = comp.AddSyntaxTrees(t1); Assert.Equal(2, comp.SyntaxTrees.Length); Assert.Contains(t1, comp.SyntaxTrees); Assert.False(comp.SyntaxTrees.Contains(SyntaxFactory.ParseSyntaxTree(s1))); comp = comp.AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(s1)); Assert.Equal(3, comp.SyntaxTrees.Length); // Replace an existing item with another valid item comp = comp.ReplaceSyntaxTree(t1, SyntaxFactory.ParseSyntaxTree(s1)); Assert.Equal(3, comp.SyntaxTrees.Length); // Replace an existing item with same item comp = comp.AddSyntaxTrees(t1).ReplaceSyntaxTree(t1, t1); Assert.Equal(4, comp.SyntaxTrees.Length); // add again and verify that it throws Assert.Throws<ArgumentException>(() => comp.AddSyntaxTrees(t1)); // replace with existing and verify that it throws Assert.Throws<ArgumentException>(() => comp.ReplaceSyntaxTree(t1, comp.SyntaxTrees[0])); // SyntaxTrees have reference equality. This removal should fail. Assert.Throws<ArgumentException>(() => comp = comp.RemoveSyntaxTrees(SyntaxFactory.ParseSyntaxTree(s1))); Assert.Equal(4, comp.SyntaxTrees.Length); // Remove non-existing item Assert.Throws<ArgumentException>(() => comp = comp.RemoveSyntaxTrees(withErrorTree)); Assert.Equal(4, comp.SyntaxTrees.Length); // Add syntaxtree with error comp = comp.AddSyntaxTrees(withErrorTree1); var error = comp.GetDiagnostics(); Assert.InRange(comp.GetDiagnostics().Count(), 0, int.MaxValue); Assert.InRange(comp.GetDeclarationDiagnostics().Count(), 0, int.MaxValue); Assert.True(comp.SyntaxTrees.Contains(t1)); SyntaxTree t4 = SyntaxFactory.ParseSyntaxTree("Using System;"); SyntaxTree t5 = SyntaxFactory.ParseSyntaxTree("Usingsssssssssssss System;"); SyntaxTree t6 = SyntaxFactory.ParseSyntaxTree("Import System;"); // Overload with Hashset var hs = new HashSet<SyntaxTree> { t4, t5, t6 }; var compCollection = CSharpCompilation.Create("Compilation", syntaxTrees: hs); compCollection = compCollection.RemoveSyntaxTrees(hs); Assert.Equal(0, compCollection.SyntaxTrees.Length); compCollection = compCollection.AddSyntaxTrees(hs).RemoveSyntaxTrees(t4, t5, t6); Assert.Equal(0, compCollection.SyntaxTrees.Length); // Overload with Collection var col = new Collection<SyntaxTree> { t4, t5, t6 }; compCollection = CSharpCompilation.Create("Compilation", syntaxTrees: col); compCollection = compCollection.RemoveSyntaxTrees(t4, t5, t6); Assert.Equal(0, compCollection.SyntaxTrees.Length); Assert.Throws<ArgumentException>(() => compCollection = compCollection.AddSyntaxTrees(t4, t5).RemoveSyntaxTrees(col)); Assert.Equal(0, compCollection.SyntaxTrees.Length); // Overload with ConcurrentStack var stack = new ConcurrentStack<SyntaxTree> { }; stack.Push(t4); stack.Push(t5); stack.Push(t6); compCollection = CSharpCompilation.Create("Compilation", syntaxTrees: stack); compCollection = compCollection.RemoveSyntaxTrees(t4, t6, t5); Assert.Equal(0, compCollection.SyntaxTrees.Length); Assert.Throws<ArgumentException>(() => compCollection = compCollection.AddSyntaxTrees(t4, t6).RemoveSyntaxTrees(stack)); Assert.Equal(0, compCollection.SyntaxTrees.Length); // Overload with ConcurrentQueue var queue = new ConcurrentQueue<SyntaxTree> { }; queue.Enqueue(t4); queue.Enqueue(t5); queue.Enqueue(t6); compCollection = CSharpCompilation.Create("Compilation", syntaxTrees: queue); compCollection = compCollection.RemoveSyntaxTrees(t4, t6, t5); Assert.Equal(0, compCollection.SyntaxTrees.Length); Assert.Throws<ArgumentException>(() => compCollection = compCollection.AddSyntaxTrees(t4, t6).RemoveSyntaxTrees(queue)); Assert.Equal(0, compCollection.SyntaxTrees.Length); // Get valid binding var bind = comp.GetSemanticModel(syntaxTree: t1); Assert.Equal(t1, bind.SyntaxTree); Assert.Equal("C#", bind.Language); // Remove syntaxtree without error comp = comp.RemoveSyntaxTrees(t1); Assert.InRange(comp.GetDiagnostics().Count(), 0, int.MaxValue); // Remove syntaxtree with error comp = comp.RemoveSyntaxTrees(withErrorTree1); var e = comp.GetDiagnostics(cancellationToken: default(CancellationToken)); Assert.Equal(0, comp.GetDiagnostics(cancellationToken: default(CancellationToken)).Count()); // Add syntaxtree which is VB language comp = comp.AddSyntaxTrees(withErrorTreeVB); error = comp.GetDiagnostics(cancellationToken: CancellationToken.None); Assert.InRange(comp.GetDiagnostics().Count(), 0, int.MaxValue); comp = comp.RemoveSyntaxTrees(withErrorTreeVB); Assert.Equal(0, comp.GetDiagnostics().Count()); // Add syntaxtree with error comp = comp.AddSyntaxTrees(withWarning); error = comp.GetDeclarationDiagnostics(); Assert.InRange(error.Count(), 1, int.MaxValue); comp = comp.RemoveSyntaxTrees(withWarning); Assert.Equal(0, comp.GetDiagnostics().Count()); // Compilation.Create with syntaxtree with a non-CompilationUnit root node: should throw an ArgumentException. Assert.False(withExpressionRootTree.HasCompilationUnitRoot, "how did we get a CompilationUnit root?"); Assert.Throws<ArgumentException>(() => CSharpCompilation.Create("Compilation", new SyntaxTree[] { withExpressionRootTree })); // AddSyntaxTrees with a non-CompilationUnit root node: should throw an ArgumentException. Assert.Throws<ArgumentException>(() => comp.AddSyntaxTrees(withExpressionRootTree)); // ReplaceSyntaxTrees syntaxtree with a non-CompilationUnit root node: should throw an ArgumentException. Assert.Throws<ArgumentException>(() => comp.ReplaceSyntaxTree(comp.SyntaxTrees[0], withExpressionRootTree)); } [Fact] public void ChainedOperations() { var s1 = "using System.Linq;"; var s2 = ""; var s3 = "Import System"; SyntaxTree t1 = SyntaxFactory.ParseSyntaxTree(s1); SyntaxTree t2 = SyntaxFactory.ParseSyntaxTree(s2); SyntaxTree t3 = SyntaxFactory.ParseSyntaxTree(s3); var listSyntaxTree = new List<SyntaxTree>(); listSyntaxTree.Add(t1); listSyntaxTree.Add(t2); // Remove second SyntaxTree CSharpCompilation comp = CSharpCompilation.Create(options: TestOptions.ReleaseDll, assemblyName: "Compilation", references: null, syntaxTrees: null); comp = comp.AddSyntaxTrees(listSyntaxTree).RemoveSyntaxTrees(t2); Assert.Equal(1, comp.SyntaxTrees.Length); // Remove mid SyntaxTree listSyntaxTree.Add(t3); comp = comp.RemoveSyntaxTrees(t1).AddSyntaxTrees(listSyntaxTree).RemoveSyntaxTrees(t2); Assert.Equal(2, comp.SyntaxTrees.Length); // remove list listSyntaxTree.Remove(t2); comp = comp.AddSyntaxTrees().RemoveSyntaxTrees(listSyntaxTree); comp = comp.AddSyntaxTrees(listSyntaxTree).RemoveSyntaxTrees(listSyntaxTree); Assert.Equal(0, comp.SyntaxTrees.Length); listSyntaxTree.Clear(); listSyntaxTree.Add(t1); listSyntaxTree.Add(t1); // Chained operation count > 2 Assert.Throws<ArgumentException>(() => comp = comp.AddSyntaxTrees(listSyntaxTree).AddReferences().ReplaceSyntaxTree(t1, t2)); comp = comp.AddSyntaxTrees(t1).AddReferences().ReplaceSyntaxTree(t1, t2); Assert.Equal(1, comp.SyntaxTrees.Length); Assert.Equal(0, comp.ExternalReferences.Length); // Create compilation with args is disordered CSharpCompilation comp1 = CSharpCompilation.Create(assemblyName: "Compilation", syntaxTrees: null, options: TestOptions.ReleaseDll, references: null); var ref1 = Net451.mscorlib; var listRef = new List<MetadataReference>(); listRef.Add(ref1); listRef.Add(ref1); // Remove with no args comp1 = comp1.AddReferences(listRef).AddSyntaxTrees(t1).RemoveReferences().RemoveSyntaxTrees(); Assert.Equal(1, comp1.ExternalReferences.Length); Assert.Equal(1, comp1.SyntaxTrees.Length); } [WorkItem(713356, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/713356")] [ClrOnlyFact] public void MissedModuleA() { var netModule1 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a1", source: new string[] { "public class C1 {}" }); netModule1.VerifyEmitDiagnostics(); var netModule2 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a2", references: new MetadataReference[] { netModule1.EmitToImageReference() }, source: new string[] { @" public class C2 { public static void M() { var a = new C1(); } }" }); netModule2.VerifyEmitDiagnostics(); var assembly = CreateCompilation( options: TestOptions.ReleaseExe, assemblyName: "a", references: new MetadataReference[] { netModule2.EmitToImageReference() }, source: new string[] { @" public class C3 { public static void Main(string[] args) { var a = new C2(); } }" }); assembly.VerifyEmitDiagnostics( Diagnostic(ErrorCode.ERR_MissingNetModuleReference).WithArguments("a1.netmodule")); assembly = CreateCompilation( options: TestOptions.ReleaseExe, assemblyName: "a", references: new MetadataReference[] { netModule1.EmitToImageReference(), netModule2.EmitToImageReference() }, source: new string[] { @" public class C3 { public static void Main(string[] args) { var a = new C2(); } }" }); assembly.VerifyEmitDiagnostics(); CompileAndVerify(assembly); } [WorkItem(713356, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/713356")] [Fact] public void MissedModuleB_OneError() { var netModule1 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a1", source: new string[] { "public class C1 {}" }); netModule1.VerifyEmitDiagnostics(); var netModule2 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a2", references: new MetadataReference[] { netModule1.EmitToImageReference() }, source: new string[] { @" public class C2 { public static void M() { var a = new C1(); } }" }); netModule2.VerifyEmitDiagnostics(); var netModule3 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a3", references: new MetadataReference[] { netModule1.EmitToImageReference() }, source: new string[] { @" public class C2a { public static void M() { var a = new C1(); } }" }); netModule3.VerifyEmitDiagnostics(); var assembly = CreateCompilation( options: TestOptions.ReleaseExe, assemblyName: "a", references: new MetadataReference[] { netModule2.EmitToImageReference(), netModule3.EmitToImageReference() }, source: new string[] { @" public class C3 { public static void Main(string[] args) { var a = new C2(); } }" }); assembly.VerifyEmitDiagnostics( Diagnostic(ErrorCode.ERR_MissingNetModuleReference).WithArguments("a1.netmodule")); } [WorkItem(718500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718500")] [WorkItem(716762, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/716762")] [Fact] public void MissedModuleB_NoErrorForUnmanagedModules() { var netModule1 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a1", source: new string[] { @" using System; using System.Runtime.InteropServices; public class C2 { [DllImport(""user32.dll"", CharSet = CharSet.Unicode)] public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); }" }); netModule1.VerifyEmitDiagnostics(); var assembly = CreateCompilation( options: TestOptions.ReleaseExe, assemblyName: "a", references: new MetadataReference[] { netModule1.EmitToImageReference() }, source: new string[] { @" public class C3 { public static void Main(string[] args) { var a = new C2(); } }" }); assembly.VerifyEmitDiagnostics(); } [WorkItem(715872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715872")] [Fact] public void MissedModuleC() { var netModule1 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a1", source: new string[] { "public class C1 {}" }); netModule1.VerifyEmitDiagnostics(); var netModule2 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a1", references: new MetadataReference[] { netModule1.EmitToImageReference() }, source: new string[] { @" public class C2 { public static void M() { var a = new C1(); } }" }); netModule2.VerifyEmitDiagnostics(); var assembly = CreateCompilation( options: TestOptions.ReleaseExe, assemblyName: "a", references: new MetadataReference[] { netModule1.EmitToImageReference(), netModule2.EmitToImageReference() }, source: new string[] { @" public class C3 { public static void Main(string[] args) { var a = new C2(); } }" }); assembly.VerifyEmitDiagnostics(Diagnostic(ErrorCode.ERR_NetModuleNameMustBeUnique).WithArguments("a1.netmodule")); } [Fact] public void MixedRefType() { var vbComp = VB.VisualBasicCompilation.Create("CompilationVB"); var comp = CSharpCompilation.Create("Compilation"); vbComp = vbComp.AddReferences(SystemRef); // Add VB reference to C# compilation foreach (var item in vbComp.References) { comp = comp.AddReferences(item); comp = comp.ReplaceReference(item, item); } Assert.Equal(1, comp.ExternalReferences.Length); var text1 = @"class A {}"; var comp1 = CSharpCompilation.Create("Test1", new[] { SyntaxFactory.ParseSyntaxTree(text1) }); var comp2 = CSharpCompilation.Create("Test2", new[] { SyntaxFactory.ParseSyntaxTree(text1) }); var compRef1 = comp1.ToMetadataReference(); var compRef2 = comp2.ToMetadataReference(); var compRef = vbComp.ToMetadataReference(embedInteropTypes: true); var ref1 = Net451.mscorlib; var ref2 = Net451.System; // Add CompilationReference comp = CSharpCompilation.Create( "Test1", new[] { SyntaxFactory.ParseSyntaxTree(text1) }, new MetadataReference[] { compRef1, compRef2 }); Assert.Equal(2, comp.ExternalReferences.Length); Assert.True(comp.References.Contains(compRef1)); Assert.True(comp.References.Contains(compRef2)); var smb = comp.GetReferencedAssemblySymbol(compRef1); Assert.Equal(SymbolKind.Assembly, smb.Kind); Assert.Equal("Test1", smb.Identity.Name, StringComparer.OrdinalIgnoreCase); // Mixed reference type comp = comp.AddReferences(ref1); Assert.Equal(3, comp.ExternalReferences.Length); Assert.True(comp.References.Contains(ref1)); // Replace Compilation reference with Assembly file reference comp = comp.ReplaceReference(compRef2, ref2); Assert.Equal(3, comp.ExternalReferences.Length); Assert.True(comp.References.Contains(ref2)); // Replace Assembly file reference with Compilation reference comp = comp.ReplaceReference(ref1, compRef2); Assert.Equal(3, comp.ExternalReferences.Length); Assert.True(comp.References.Contains(compRef2)); var modRef1 = TestReferences.MetadataTests.NetModule01.ModuleCS00; // Add Module file reference comp = comp.AddReferences(modRef1); // Not implemented code //var modSmb = comp.GetReferencedModuleSymbol(modRef1); //Assert.Equal("ModuleCS00.mod", modSmb.Name); //Assert.Equal(4, comp.References.Count); //Assert.True(comp.References.Contains(modRef1)); //smb = comp.GetReferencedAssemblySymbol(reference: modRef1); //Assert.Equal(smb.Kind, SymbolKind.Assembly); //Assert.Equal("Test1", smb.Identity.Name, StringComparer.OrdinalIgnoreCase); // GetCompilationNamespace Not implemented(Derived Class AssemblySymbol) //var m = smb.GlobalNamespace.GetMembers(); //var nsSmb = smb.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; //var ns = comp.GetCompilationNamespace(ns: nsSmb); //Assert.Equal(ns.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); //var asbSmb = smb as Symbol; //var ns1 = comp.GetCompilationNamespace(ns: asbSmb as NamespaceSymbol); //Assert.Equal(ns1.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns1.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); // Get Referenced Module Symbol //var moduleSmb = comp.GetReferencedModuleSymbol(reference: modRef1); //Assert.Equal(SymbolKind.NetModule, moduleSmb.Kind); //Assert.Equal("ModuleCS00.mod", moduleSmb.Name, StringComparer.OrdinalIgnoreCase); // GetCompilationNamespace Not implemented(Derived Class ModuleSymbol) //nsSmb = moduleSmb.GlobalNamespace.GetMembers("Runtime").Single() as NamespaceSymbol; //ns = comp.GetCompilationNamespace(ns: nsSmb); //Assert.Equal(ns.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); //var modSmbol = moduleSmb as Symbol; //ns1 = comp.GetCompilationNamespace(ns: modSmbol as NamespaceSymbol); //Assert.Equal(ns1.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns1.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); // Get Compilation Namespace //nsSmb = comp.GlobalNamespace; //ns = comp.GetCompilationNamespace(ns: nsSmb); //Assert.Equal(ns.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); // GetCompilationNamespace Not implemented(Derived Class MergedNamespaceSymbol) //NamespaceSymbol merged = MergedNamespaceSymbol.Create(new NamespaceExtent(new MockAssemblySymbol("Merged")), null, null); //ns = comp.GetCompilationNamespace(ns: merged); //Assert.Equal(ns.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); // GetCompilationNamespace Not implemented(Derived Class RetargetingNamespaceSymbol) //Retargeting.RetargetingNamespaceSymbol retargetSmb = nsSmb as Retargeting.RetargetingNamespaceSymbol; //ns = comp.GetCompilationNamespace(ns: retargetSmb); //Assert.Equal(ns.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); // GetCompilationNamespace Not implemented(Derived Class PENamespaceSymbol) //Symbols.Metadata.PE.PENamespaceSymbol pensSmb = nsSmb as Symbols.Metadata.PE.PENamespaceSymbol; //ns = comp.GetCompilationNamespace(ns: pensSmb); //Assert.Equal(ns.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); // Replace Module file reference with compilation reference comp = comp.RemoveReferences(compRef1).ReplaceReference(modRef1, compRef1); Assert.Equal(3, comp.ExternalReferences.Length); // Check the reference order after replace Assert.True(comp.ExternalReferences[2] is CSharpCompilationReference, "Expected compilation reference"); Assert.Equal(compRef1, comp.ExternalReferences[2]); // Replace compilation Module file reference with Module file reference comp = comp.ReplaceReference(compRef1, modRef1); // Check the reference order after replace Assert.Equal(3, comp.ExternalReferences.Length); Assert.Equal(MetadataImageKind.Module, comp.ExternalReferences[2].Properties.Kind); Assert.Equal(modRef1, comp.ExternalReferences[2]); // Add VB compilation ref Assert.Throws<ArgumentException>(() => comp.AddReferences(compRef)); foreach (var item in comp.References) { comp = comp.RemoveReferences(item); } Assert.Equal(0, comp.ExternalReferences.Length); // Not Implemented // var asmByteRef = MetadataReference.CreateFromImage(new byte[5], embedInteropTypes: true); //var asmObjectRef = new AssemblyObjectReference(assembly: System.Reflection.Assembly.GetAssembly(typeof(object)),embedInteropTypes :true); //comp =comp.AddReferences(asmByteRef, asmObjectRef); //Assert.Equal(2, comp.References.Count); //Assert.Equal(ReferenceKind.AssemblyBytes, comp.References[0].Kind); //Assert.Equal(ReferenceKind.AssemblyObject , comp.References[1].Kind); //Assert.Equal(asmByteRef, comp.References[0]); //Assert.Equal(asmObjectRef, comp.References[1]); //Assert.True(comp.References[0].EmbedInteropTypes); //Assert.True(comp.References[1].EmbedInteropTypes); } [Fact] public void NegGetCompilationNamespace() { var comp = CSharpCompilation.Create("Compilation"); // Throw exception when the parameter of GetCompilationNamespace is null Assert.Throws<NullReferenceException>( delegate { comp.GetCompilationNamespace(namespaceSymbol: (INamespaceSymbol)null); }); Assert.Throws<NullReferenceException>( delegate { comp.GetCompilationNamespace(namespaceSymbol: (NamespaceSymbol)null); }); } [WorkItem(537623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537623")] [Fact] public void NegCreateCompilation() { Assert.Throws<ArgumentNullException>(() => CSharpCompilation.Create("goo", syntaxTrees: new SyntaxTree[] { null })); Assert.Throws<ArgumentNullException>(() => CSharpCompilation.Create("goo", references: new MetadataReference[] { null })); } [WorkItem(537637, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537637")] [Fact] public void NegGetSymbol() { // Create Compilation with miss mid args var comp = CSharpCompilation.Create("Compilation"); Assert.Null(comp.GetReferencedAssemblySymbol(reference: MscorlibRef)); var modRef1 = TestReferences.MetadataTests.NetModule01.ModuleCS00; // Get not exist Referenced Module Symbol Assert.Null(comp.GetReferencedModuleSymbol(modRef1)); // Throw exception when the parameter of GetReferencedAssemblySymbol is null Assert.Throws<ArgumentNullException>( delegate { comp.GetReferencedAssemblySymbol(null); }); // Throw exception when the parameter of GetReferencedModuleSymbol is null Assert.Throws<ArgumentNullException>( delegate { var modSmb1 = comp.GetReferencedModuleSymbol(null); }); } [WorkItem(537778, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537778")] // Throw exception when the parameter of the parameter type of GetReferencedAssemblySymbol is VB.CompilationReference [Fact] public void NegGetSymbol1() { var opt = TestOptions.ReleaseDll; var comp = CSharpCompilation.Create("Compilation"); var vbComp = VB.VisualBasicCompilation.Create("CompilationVB"); vbComp = vbComp.AddReferences(SystemRef); var compRef = vbComp.ToMetadataReference(); Assert.Throws<ArgumentException>(() => comp.AddReferences(compRef)); // Throw exception when the parameter of GetBinding is null Assert.Throws<ArgumentNullException>( delegate { comp.GetSemanticModel(null); }); // Throw exception when the parameter of GetTypeByNameAndArity is NULL //Assert.Throws<Exception>( //delegate //{ // comp.GetTypeByNameAndArity(fullName: null, arity: 1); //}); // Throw exception when the parameter of GetTypeByNameAndArity is less than 0 //Assert.Throws<Exception>( //delegate //{ // comp.GetTypeByNameAndArity(string.Empty, -4); //}); } // Add already existing item [Fact, WorkItem(537574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537574")] public void NegReference2() { var ref1 = Net451.mscorlib; var ref2 = Net451.System; var ref3 = Net451.SystemData; var ref4 = Net451.SystemXml; var comp = CSharpCompilation.Create("Compilation"); comp = comp.AddReferences(ref1, ref1); Assert.Equal(1, comp.ExternalReferences.Length); Assert.Equal(MetadataImageKind.Assembly, comp.ExternalReferences[0].Properties.Kind); Assert.Equal(ref1, comp.ExternalReferences[0]); var listRef = new List<MetadataReference> { ref1, ref2, ref3, ref4 }; // Chained operation count > 3 // ReplaceReference throws if the reference to be replaced is not found. comp = comp.AddReferences(listRef).AddReferences(ref2).RemoveReferences(ref1, ref3, ref4).ReplaceReference(ref2, ref2); Assert.Equal(1, comp.ExternalReferences.Length); Assert.Equal(MetadataImageKind.Assembly, comp.ExternalReferences[0].Properties.Kind); Assert.Equal(ref2, comp.ExternalReferences[0]); Assert.Throws<ArgumentException>(() => comp.AddReferences(listRef).AddReferences(ref2).RemoveReferences(ref1, ref2, ref3, ref4).ReplaceReference(ref2, ref2)); } // Add a new invalid item [Fact, WorkItem(537575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537575")] public void NegReference3() { var ref1 = InvalidRef; var comp = CSharpCompilation.Create("Compilation"); // Remove non-existing item Assert.Throws<ArgumentException>(() => comp = comp.RemoveReferences(ref1)); // Add a new invalid item comp = comp.AddReferences(ref1); Assert.Equal(1, comp.ExternalReferences.Length); // Replace a non-existing item with another invalid item Assert.Throws<ArgumentException>(() => comp = comp.ReplaceReference(MscorlibRef, ref1)); Assert.Equal(1, comp.ExternalReferences.Length); } // Replace a non-existing item with null [Fact, WorkItem(537567, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537567")] public void NegReference4() { var ref1 = Net451.mscorlib; var comp = CSharpCompilation.Create("Compilation"); Assert.Throws<ArgumentException>( delegate { comp = comp.ReplaceReference(ref1, null); }); // Replace null and the arg order of replace is vise Assert.Throws<ArgumentNullException>( delegate { comp = comp.ReplaceReference(newReference: ref1, oldReference: null); }); } // Replace a non-existing item with another valid item [Fact, WorkItem(537566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537566")] public void NegReference5() { var ref1 = Net451.mscorlib; var ref2 = Net451.SystemXml; var comp = CSharpCompilation.Create("Compilation"); Assert.Throws<ArgumentException>( delegate { comp = comp.ReplaceReference(ref1, ref2); }); SyntaxTree t1 = SyntaxFactory.ParseSyntaxTree("Using System;"); // Replace a non-existing item with another valid item and disorder the args Assert.Throws<ArgumentException>( delegate { comp.ReplaceReference(newReference: Net451.System, oldReference: ref2); }); Assert.Equal(0, comp.SyntaxTrees.Length); Assert.Throws<ArgumentException>(() => comp.ReplaceSyntaxTree(newTree: SyntaxFactory.ParseSyntaxTree("Using System;"), oldTree: t1)); Assert.Equal(0, comp.SyntaxTrees.Length); } [WorkItem(527256, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527256")] // Throw exception when the parameter of SyntaxTrees.Contains is null [Fact] public void NegSyntaxTreesContains() { var comp = CSharpCompilation.Create("Compilation"); Assert.False(comp.SyntaxTrees.Contains(null)); } [WorkItem(537784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537784")] // Throw exception when the parameter of GetSpecialType() is out of range [Fact] public void NegGetSpecialType() { var comp = CSharpCompilation.Create("Compilation"); // Throw exception when the parameter of GetBinding is out of range Assert.Throws<ArgumentOutOfRangeException>( delegate { comp.GetSpecialType((SpecialType)100); }); Assert.Throws<ArgumentOutOfRangeException>( delegate { comp.GetSpecialType(SpecialType.None); }); Assert.Throws<ArgumentOutOfRangeException>( delegate { comp.GetSpecialType((SpecialType)000); }); Assert.Throws<ArgumentOutOfRangeException>( delegate { comp.GetSpecialType(default(SpecialType)); }); } [WorkItem(538168, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538168")] // Replace a non-existing item with another valid item and disorder the args [Fact] public void NegTree2() { var comp = CSharpCompilation.Create("API"); SyntaxTree t1 = SyntaxFactory.ParseSyntaxTree("Using System;"); Assert.Throws<ArgumentException>( delegate { comp = comp.ReplaceSyntaxTree(newTree: SyntaxFactory.ParseSyntaxTree("Using System;"), oldTree: t1); }); } [WorkItem(537576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537576")] // Add already existing item [Fact] public void NegSynTree1() { var comp = CSharpCompilation.Create("Compilation"); SyntaxTree t1 = SyntaxFactory.ParseSyntaxTree("Using System;"); Assert.Throws<ArgumentException>(() => (comp.AddSyntaxTrees(t1, t1))); Assert.Equal(0, comp.SyntaxTrees.Length); } [Fact] public void NegSynTree() { var comp = CSharpCompilation.Create("Compilation"); SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("Using Goo;"); // Throw exception when add null SyntaxTree Assert.Throws<ArgumentNullException>( delegate { comp.AddSyntaxTrees(null); }); // Throw exception when Remove null SyntaxTree Assert.Throws<ArgumentNullException>( delegate { comp.RemoveSyntaxTrees(null); }); // No exception when replacing a SyntaxTree with null var compP = comp.AddSyntaxTrees(syntaxTree); comp = compP.ReplaceSyntaxTree(syntaxTree, null); Assert.Equal(0, comp.SyntaxTrees.Length); // Throw exception when remove null SyntaxTree Assert.Throws<ArgumentNullException>( delegate { comp = comp.ReplaceSyntaxTree(null, syntaxTree); }); var s1 = "Imports System.Text"; SyntaxTree t1 = VB.VisualBasicSyntaxTree.ParseText(s1); SyntaxTree t2 = t1; var t3 = t2; var vbComp = VB.VisualBasicCompilation.Create("CompilationVB"); vbComp = vbComp.AddSyntaxTrees(t1, VB.VisualBasicSyntaxTree.ParseText("Using Goo;")); // Throw exception when cast SyntaxTree foreach (var item in vbComp.SyntaxTrees) { t3 = item; Exception invalidCastSynTreeEx = Assert.Throws<InvalidCastException>( delegate { comp = comp.AddSyntaxTrees(t3); }); invalidCastSynTreeEx = Assert.Throws<InvalidCastException>( delegate { comp = comp.RemoveSyntaxTrees(t3); }); invalidCastSynTreeEx = Assert.Throws<InvalidCastException>( delegate { comp = comp.ReplaceSyntaxTree(t3, t3); }); } // Get Binding with tree is not exist SyntaxTree t4 = SyntaxFactory.ParseSyntaxTree(s1); Assert.Throws<ArgumentException>( delegate { comp.RemoveSyntaxTrees(new SyntaxTree[] { t4 }).GetSemanticModel(t4); }); } [Fact] public void GetEntryPoint_Exe() { var source = @" class A { static void Main() { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var mainMethod = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMember<MethodSymbol>("Main"); Assert.Equal(mainMethod, compilation.GetEntryPoint(default(CancellationToken))); var entryPointAndDiagnostics = compilation.GetEntryPointAndDiagnostics(default(CancellationToken)); Assert.Equal(mainMethod, entryPointAndDiagnostics.MethodSymbol); entryPointAndDiagnostics.Diagnostics.Verify(); } [Fact] public void GetEntryPoint_Dll() { var source = @" class A { static void Main() { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); Assert.Null(compilation.GetEntryPoint(default(CancellationToken))); Assert.Same(CSharpCompilation.EntryPoint.None, compilation.GetEntryPointAndDiagnostics(default(CancellationToken))); } [Fact] public void GetEntryPoint_Module() { var source = @" class A { static void Main() { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseModule); compilation.VerifyDiagnostics(); Assert.Null(compilation.GetEntryPoint(default(CancellationToken))); Assert.Same(CSharpCompilation.EntryPoint.None, compilation.GetEntryPointAndDiagnostics(default(CancellationToken))); } [Fact] public void CreateCompilationForModule() { var source = @" class A { static void Main() { } } "; // equivalent of csc with no /moduleassemblyname specified: var compilation = CSharpCompilation.Create(assemblyName: null, options: TestOptions.ReleaseModule, syntaxTrees: new[] { Parse(source) }, references: new[] { MscorlibRef }); compilation.VerifyEmitDiagnostics(); Assert.Null(compilation.AssemblyName); Assert.Equal("?", compilation.Assembly.Name); Assert.Equal("?", compilation.Assembly.Identity.Name); // no name is allowed for assembly as well, although it isn't useful: compilation = CSharpCompilation.Create(assemblyName: null, options: TestOptions.ReleaseDll, syntaxTrees: new[] { Parse(source) }, references: new[] { MscorlibRef }); compilation.VerifyEmitDiagnostics(); Assert.Null(compilation.AssemblyName); Assert.Equal("?", compilation.Assembly.Name); Assert.Equal("?", compilation.Assembly.Identity.Name); // equivalent of csc with /moduleassemblyname specified: compilation = CSharpCompilation.Create(assemblyName: "ModuleAssemblyName", options: TestOptions.ReleaseModule, syntaxTrees: new[] { Parse(source) }, references: new[] { MscorlibRef }); compilation.VerifyDiagnostics(); Assert.Equal("ModuleAssemblyName", compilation.AssemblyName); Assert.Equal("ModuleAssemblyName", compilation.Assembly.Name); Assert.Equal("ModuleAssemblyName", compilation.Assembly.Identity.Name); } [WorkItem(8506, "https://github.com/dotnet/roslyn/issues/8506")] [WorkItem(17403, "https://github.com/dotnet/roslyn/issues/17403")] [Fact] public void CrossCorlibSystemObjectReturnType_Script() { // MinAsyncCorlibRef corlib is used since it provides just enough corlib type definitions // and Task APIs necessary for script hosting are provided by MinAsyncRef. This ensures that // `System.Object, mscorlib, Version=4.0.0.0` will not be provided (since it's unversioned). // // In the original bug, Xamarin iOS, Android, and Mac Mobile profile corlibs were // realistic cross-compilation targets. void AssertCompilationCorlib(CSharpCompilation compilation) { Assert.True(compilation.IsSubmission); var taskOfT = compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T); var taskOfObject = taskOfT.Construct(compilation.ObjectType); var entryPoint = compilation.GetEntryPoint(default(CancellationToken)); Assert.Same(compilation.ObjectType.ContainingAssembly, taskOfT.ContainingAssembly); Assert.Same(compilation.ObjectType.ContainingAssembly, taskOfObject.ContainingAssembly); Assert.Equal(taskOfObject, entryPoint.ReturnType); } var firstCompilation = CSharpCompilation.CreateScriptCompilation( "submission-assembly-1", references: new[] { MinAsyncCorlibRef }, syntaxTree: Parse("true", options: TestOptions.Script) ).VerifyDiagnostics(); AssertCompilationCorlib(firstCompilation); var secondCompilation = CSharpCompilation.CreateScriptCompilation( "submission-assembly-2", previousScriptCompilation: firstCompilation, syntaxTree: Parse("false", options: TestOptions.Script)) .WithScriptCompilationInfo(new CSharpScriptCompilationInfo(firstCompilation, null, null)) .VerifyDiagnostics(); AssertCompilationCorlib(secondCompilation); Assert.Same(firstCompilation.ObjectType, secondCompilation.ObjectType); Assert.Null(new CSharpScriptCompilationInfo(null, null, null) .WithPreviousScriptCompilation(firstCompilation) .ReturnTypeOpt); } [WorkItem(3719, "https://github.com/dotnet/roslyn/issues/3719")] [Fact] public void GetEntryPoint_Script() { var source = @"System.Console.WriteLine(1);"; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Script); compilation.VerifyDiagnostics(); var scriptMethod = compilation.GetMember<MethodSymbol>("Script.<Main>"); Assert.NotNull(scriptMethod); var method = compilation.GetEntryPoint(default(CancellationToken)); Assert.Equal(method, scriptMethod); var entryPoint = compilation.GetEntryPointAndDiagnostics(default(CancellationToken)); Assert.Equal(entryPoint.MethodSymbol, scriptMethod); } [Fact] public void GetEntryPoint_Script_MainIgnored() { var source = @" class A { static void Main() { } } "; var compilation = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (4,17): warning CS7022: The entry point of the program is global script code; ignoring 'A.Main()' entry point. // static void Main() { } Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("A.Main()").WithLocation(4, 17)); var scriptMethod = compilation.GetMember<MethodSymbol>("Script.<Main>"); Assert.NotNull(scriptMethod); var entryPoint = compilation.GetEntryPointAndDiagnostics(default(CancellationToken)); Assert.Equal(entryPoint.MethodSymbol, scriptMethod); entryPoint.Diagnostics.Verify( // (4,17): warning CS7022: The entry point of the program is global script code; ignoring 'A.Main()' entry point. // static void Main() { } Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("A.Main()").WithLocation(4, 17)); } [Fact] public void GetEntryPoint_Submission() { var source = @"1 + 1"; var compilation = CSharpCompilation.CreateScriptCompilation("sub", references: new[] { MscorlibRef }, syntaxTree: Parse(source, options: TestOptions.Script)); compilation.VerifyDiagnostics(); var scriptMethod = compilation.GetMember<MethodSymbol>("Script.<Factory>"); Assert.NotNull(scriptMethod); var method = compilation.GetEntryPoint(default(CancellationToken)); Assert.Equal(method, scriptMethod); var entryPoint = compilation.GetEntryPointAndDiagnostics(default(CancellationToken)); Assert.Equal(entryPoint.MethodSymbol, scriptMethod); entryPoint.Diagnostics.Verify(); } [Fact] public void GetEntryPoint_Submission_MainIgnored() { var source = @" class A { static void Main() { } } "; var compilation = CSharpCompilation.CreateScriptCompilation("sub", references: new[] { MscorlibRef }, syntaxTree: Parse(source, options: TestOptions.Script)); compilation.VerifyDiagnostics( // (4,17): warning CS7022: The entry point of the program is global script code; ignoring 'A.Main()' entry point. // static void Main() { } Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("A.Main()").WithLocation(4, 17)); Assert.True(compilation.IsSubmission); var scriptMethod = compilation.GetMember<MethodSymbol>("Script.<Factory>"); Assert.NotNull(scriptMethod); var entryPoint = compilation.GetEntryPointAndDiagnostics(default(CancellationToken)); Assert.Equal(entryPoint.MethodSymbol, scriptMethod); entryPoint.Diagnostics.Verify( // (4,17): warning CS7022: The entry point of the program is global script code; ignoring 'A.Main()' entry point. // static void Main() { } Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("A.Main()").WithLocation(4, 17)); } [Fact] public void GetEntryPoint_MainType() { var source = @" class A { static void Main() { } } class B { static void Main() { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithMainTypeName("B")); compilation.VerifyDiagnostics(); var mainMethod = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B").GetMember<MethodSymbol>("Main"); Assert.Equal(mainMethod, compilation.GetEntryPoint(default(CancellationToken))); var entryPointAndDiagnostics = compilation.GetEntryPointAndDiagnostics(default(CancellationToken)); Assert.Equal(mainMethod, entryPointAndDiagnostics.MethodSymbol); entryPointAndDiagnostics.Diagnostics.Verify(); } [Fact] public void CanReadAndWriteDefaultWin32Res() { var comp = CSharpCompilation.Create("Compilation"); var mft = new MemoryStream(new byte[] { 0, 1, 2, 3, }); var res = comp.CreateDefaultWin32Resources(true, false, mft, null); var list = comp.MakeWin32ResourceList(res, new DiagnosticBag()); Assert.Equal(2, list.Count); } [Fact, WorkItem(750437, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/750437")] public void ConflictingAliases() { var alias = Net451.System.WithAliases(new[] { "alias" }); var text = @"extern alias alias; using alias=alias; class myClass : alias::Uri { }"; var comp = CreateEmptyCompilation(text, references: new[] { MscorlibRef, alias }); Assert.Equal(2, comp.References.Count()); Assert.Equal("alias", comp.References.Last().Properties.Aliases.Single()); comp.VerifyDiagnostics( // (2,1): error CS1537: The using alias 'alias' appeared previously in this namespace // using alias=alias; Diagnostic(ErrorCode.ERR_DuplicateAlias, "using alias=alias;").WithArguments("alias"), // (3,17): error CS0104: 'alias' is an ambiguous reference between '<global namespace>' and '<global namespace>' // class myClass : alias::Uri Diagnostic(ErrorCode.ERR_AmbigContext, "alias").WithArguments("alias", "<global namespace>", "<global namespace>")); } [WorkItem(546088, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546088")] [Fact] public void CompilationDiagsIncorrectResult() { string source1 = @" using SysAttribute = System.Attribute; using MyAttribute = MyAttribute2Attribute; public class MyAttributeAttribute : SysAttribute {} public class MyAttribute2Attribute : SysAttribute {} [MyAttribute] public class TestClass { } "; string source2 = @""; // Ask for model diagnostics first. { var compilation = CreateCompilation(source: new string[] { source1, source2 }); var tree2 = compilation.SyntaxTrees[1]; //tree for empty file var model2 = compilation.GetSemanticModel(tree2); model2.GetDiagnostics().Verify(); // None, since the file is empty. compilation.GetDiagnostics().Verify( // (8,2): error CS1614: 'MyAttribute' is ambiguous between 'MyAttribute2Attribute' and 'MyAttributeAttribute'; use either '@MyAttribute' or 'MyAttributeAttribute' // [MyAttribute] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "MyAttribute").WithArguments("MyAttribute", "MyAttribute2Attribute", "MyAttributeAttribute")); } // Ask for compilation diagnostics first. { var compilation = CreateCompilation(source: new string[] { source1, source2 }); var tree2 = compilation.SyntaxTrees[1]; //tree for empty file var model2 = compilation.GetSemanticModel(tree2); compilation.GetDiagnostics().Verify( // (10,2): error CS1614: 'MyAttribute' is ambiguous between 'MyAttribute2Attribute' and 'MyAttributeAttribute'; use either '@MyAttribute' or 'MyAttributeAttribute' // [MyAttribute] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "MyAttribute").WithArguments("MyAttribute", "MyAttribute2Attribute", "MyAttributeAttribute")); model2.GetDiagnostics().Verify(); // None, since the file is empty. } } [Fact] public void ReferenceManagerReuse_WithOptions() { var c1 = CSharpCompilation.Create("c", options: TestOptions.ReleaseDll); var c2 = c1.WithOptions(TestOptions.ReleaseExe); Assert.True(c1.ReferenceManagerEquals(c2)); c2 = c1.WithOptions(TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsApplication)); Assert.True(c1.ReferenceManagerEquals(c2)); c2 = c1.WithOptions(TestOptions.ReleaseDll); Assert.True(c1.ReferenceManagerEquals(c2)); c2 = c1.WithOptions(TestOptions.ReleaseDll.WithOutputKind(OutputKind.NetModule)); Assert.False(c1.ReferenceManagerEquals(c2)); c1 = CSharpCompilation.Create("c", options: TestOptions.ReleaseModule); c2 = c1.WithOptions(TestOptions.ReleaseExe); Assert.False(c1.ReferenceManagerEquals(c2)); c2 = c1.WithOptions(TestOptions.ReleaseDll); Assert.False(c1.ReferenceManagerEquals(c2)); c2 = c1.WithOptions(TestOptions.CreateTestOptions(OutputKind.WindowsApplication, OptimizationLevel.Debug)); Assert.False(c1.ReferenceManagerEquals(c2)); c2 = c1.WithOptions(TestOptions.DebugModule.WithAllowUnsafe(true)); Assert.True(c1.ReferenceManagerEquals(c2)); } [Fact] public void ReferenceManagerReuse_WithMetadataReferenceResolver() { var c1 = CSharpCompilation.Create("c", options: TestOptions.ReleaseDll); var c2 = c1.WithOptions(TestOptions.ReleaseDll.WithMetadataReferenceResolver(new TestMetadataReferenceResolver())); Assert.False(c1.ReferenceManagerEquals(c2)); var c3 = c1.WithOptions(TestOptions.ReleaseDll.WithMetadataReferenceResolver(c1.Options.MetadataReferenceResolver)); Assert.True(c1.ReferenceManagerEquals(c3)); } [Fact] public void ReferenceManagerReuse_WithXmlFileResolver() { var c1 = CSharpCompilation.Create("c", options: TestOptions.ReleaseDll); var c2 = c1.WithOptions(TestOptions.ReleaseDll.WithXmlReferenceResolver(new XmlFileResolver(null))); Assert.False(c1.ReferenceManagerEquals(c2)); var c3 = c1.WithOptions(TestOptions.ReleaseDll.WithXmlReferenceResolver(c1.Options.XmlReferenceResolver)); Assert.True(c1.ReferenceManagerEquals(c3)); } [Fact] public void ReferenceManagerReuse_WithName() { var c1 = CSharpCompilation.Create("c1"); var c2 = c1.WithAssemblyName("c2"); Assert.False(c1.ReferenceManagerEquals(c2)); var c3 = c1.WithAssemblyName("c1"); Assert.True(c1.ReferenceManagerEquals(c3)); var c4 = c1.WithAssemblyName(null); Assert.False(c1.ReferenceManagerEquals(c4)); var c5 = c4.WithAssemblyName(null); Assert.True(c4.ReferenceManagerEquals(c5)); } [Fact] public void ReferenceManagerReuse_WithReferences() { var c1 = CSharpCompilation.Create("c1"); var c2 = c1.WithReferences(new[] { MscorlibRef }); Assert.False(c1.ReferenceManagerEquals(c2)); var c3 = c2.WithReferences(new[] { MscorlibRef, SystemCoreRef }); Assert.False(c3.ReferenceManagerEquals(c2)); c3 = c2.AddReferences(SystemCoreRef); Assert.False(c3.ReferenceManagerEquals(c2)); c3 = c2.RemoveAllReferences(); Assert.False(c3.ReferenceManagerEquals(c2)); c3 = c2.ReplaceReference(MscorlibRef, SystemCoreRef); Assert.False(c3.ReferenceManagerEquals(c2)); c3 = c2.RemoveReferences(MscorlibRef); Assert.False(c3.ReferenceManagerEquals(c2)); } [Fact] public void ReferenceManagerReuse_WithSyntaxTrees() { var ta = Parse("class C { }", options: TestOptions.Regular10); var tb = Parse(@" class C { }", options: TestOptions.Script); var tc = Parse(@" #r ""bar"" // error: #r in regular code class D { }", options: TestOptions.Regular10); var tr = Parse(@" #r ""goo"" class C { }", options: TestOptions.Script); var ts = Parse(@" #r ""bar"" class C { }", options: TestOptions.Script); var a = CSharpCompilation.Create("c", syntaxTrees: new[] { ta }); // add: var ab = a.AddSyntaxTrees(tb); Assert.True(a.ReferenceManagerEquals(ab)); var ac = a.AddSyntaxTrees(tc); Assert.True(a.ReferenceManagerEquals(ac)); var ar = a.AddSyntaxTrees(tr); Assert.False(a.ReferenceManagerEquals(ar)); var arc = ar.AddSyntaxTrees(tc); Assert.True(ar.ReferenceManagerEquals(arc)); // remove: var ar2 = arc.RemoveSyntaxTrees(tc); Assert.True(arc.ReferenceManagerEquals(ar2)); var c = arc.RemoveSyntaxTrees(ta, tr); Assert.False(arc.ReferenceManagerEquals(c)); var none1 = c.RemoveSyntaxTrees(tc); Assert.True(c.ReferenceManagerEquals(none1)); var none2 = arc.RemoveAllSyntaxTrees(); Assert.False(arc.ReferenceManagerEquals(none2)); var none3 = ac.RemoveAllSyntaxTrees(); Assert.True(ac.ReferenceManagerEquals(none3)); // replace: var asc = arc.ReplaceSyntaxTree(tr, ts); Assert.False(arc.ReferenceManagerEquals(asc)); var brc = arc.ReplaceSyntaxTree(ta, tb); Assert.True(arc.ReferenceManagerEquals(brc)); var abc = arc.ReplaceSyntaxTree(tr, tb); Assert.False(arc.ReferenceManagerEquals(abc)); var ars = arc.ReplaceSyntaxTree(tc, ts); Assert.False(arc.ReferenceManagerEquals(ars)); } [Fact] public void ReferenceManagerReuse_WithScriptCompilationInfo() { // Note: The following results would change if we optimized sharing more: https://github.com/dotnet/roslyn/issues/43397 var c1 = CSharpCompilation.CreateScriptCompilation("c1"); Assert.NotNull(c1.ScriptCompilationInfo); Assert.Null(c1.ScriptCompilationInfo.PreviousScriptCompilation); var c2 = c1.WithScriptCompilationInfo(null); Assert.Null(c2.ScriptCompilationInfo); Assert.True(c2.ReferenceManagerEquals(c1)); var c3 = c2.WithScriptCompilationInfo(new CSharpScriptCompilationInfo(previousCompilationOpt: null, returnType: typeof(int), globalsType: null)); Assert.NotNull(c3.ScriptCompilationInfo); Assert.Null(c3.ScriptCompilationInfo.PreviousScriptCompilation); Assert.True(c3.ReferenceManagerEquals(c2)); var c4 = c3.WithScriptCompilationInfo(null); Assert.Null(c4.ScriptCompilationInfo); Assert.True(c4.ReferenceManagerEquals(c3)); var c5 = c4.WithScriptCompilationInfo(new CSharpScriptCompilationInfo(previousCompilationOpt: c1, returnType: typeof(int), globalsType: null)); Assert.False(c5.ReferenceManagerEquals(c4)); var c6 = c5.WithScriptCompilationInfo(new CSharpScriptCompilationInfo(previousCompilationOpt: c1, returnType: typeof(bool), globalsType: null)); Assert.True(c6.ReferenceManagerEquals(c5)); var c7 = c6.WithScriptCompilationInfo(new CSharpScriptCompilationInfo(previousCompilationOpt: c2, returnType: typeof(bool), globalsType: null)); Assert.False(c7.ReferenceManagerEquals(c6)); var c8 = c7.WithScriptCompilationInfo(new CSharpScriptCompilationInfo(previousCompilationOpt: null, returnType: typeof(bool), globalsType: null)); Assert.False(c8.ReferenceManagerEquals(c7)); var c9 = c8.WithScriptCompilationInfo(null); Assert.True(c9.ReferenceManagerEquals(c8)); } private sealed class EvolvingTestReference : PortableExecutableReference { private readonly IEnumerator<Metadata> _metadataSequence; public int QueryCount; public EvolvingTestReference(IEnumerable<Metadata> metadataSequence) : base(MetadataReferenceProperties.Assembly) { _metadataSequence = metadataSequence.GetEnumerator(); } protected override DocumentationProvider CreateDocumentationProvider() { return DocumentationProvider.Default; } protected override Metadata GetMetadataImpl() { QueryCount++; _metadataSequence.MoveNext(); return _metadataSequence.Current; } protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties) { throw new NotImplementedException(); } } [ConditionalFact(typeof(NoUsedAssembliesValidation), typeof(NoIOperationValidation), Reason = "IOperation skip: Compilation changes over time, adds new errors")] public void MetadataConsistencyWhileEvolvingCompilation() { var md1 = AssemblyMetadata.CreateFromImage(CreateCompilation("public class C { }").EmitToArray()); var md2 = AssemblyMetadata.CreateFromImage(CreateCompilation("public class D { }").EmitToArray()); var reference = new EvolvingTestReference(new[] { md1, md2 }); var c1 = CreateEmptyCompilation("public class Main { public static C C; }", new[] { MscorlibRef, reference, reference }); var c2 = c1.WithAssemblyName("c2"); var c3 = c2.AddSyntaxTrees(Parse("public class Main2 { public static int a; }")); var c4 = c3.WithOptions(TestOptions.DebugModule); var c5 = c4.WithReferences(new[] { MscorlibRef, reference }); c3.VerifyDiagnostics(); c1.VerifyDiagnostics(); c4.VerifyDiagnostics(); c2.VerifyDiagnostics(); Assert.Equal(1, reference.QueryCount); c5.VerifyDiagnostics( // (1,36): error CS0246: The type or namespace name 'C' could not be found (are you missing a using directive or an assembly reference?) // public class Main2 { public static C C; } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C").WithArguments("C")); Assert.Equal(2, reference.QueryCount); } [Fact] public unsafe void LinkedNetmoduleMetadataMustProvideFullPEImage() { var netModule = TestResources.MetadataTests.NetModule01.ModuleCS00; PEHeaders h = new PEHeaders(new MemoryStream(netModule)); fixed (byte* ptr = &netModule[h.MetadataStartOffset]) { using (var mdModule = ModuleMetadata.CreateFromMetadata((IntPtr)ptr, h.MetadataSize)) { var c = CSharpCompilation.Create("Goo", references: new[] { MscorlibRef, mdModule.GetReference(display: "ModuleCS00") }, options: TestOptions.ReleaseDll); c.VerifyDiagnostics( // error CS7098: Linked netmodule metadata must provide a full PE image: 'ModuleCS00'. Diagnostic(ErrorCode.ERR_LinkedNetmoduleMetadataMustProvideFullPEImage).WithArguments("ModuleCS00").WithLocation(1, 1)); } } } [Fact] public void AppConfig1() { var references = new MetadataReference[] { Net451.mscorlib, Net451.System, TestReferences.NetFx.silverlight_v5_0_5_0.System }; var compilation = CreateEmptyCompilation( new[] { Parse("") }, references, options: TestOptions.ReleaseDll.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)); compilation.VerifyDiagnostics( // error CS1703: Multiple assemblies with equivalent identity have been imported: 'System.dll' and 'System.v5.0.5.0_silverlight.dll'. Remove one of the duplicate references. Diagnostic(ErrorCode.ERR_DuplicateImport).WithArguments("System.dll (net451)", "System.v5.0.5.0_silverlight.dll")); var appConfig = new MemoryStream(Encoding.UTF8.GetBytes( @"<?xml version=""1.0"" encoding=""utf-8"" ?> <configuration> <runtime> <assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1""> <supportPortability PKT=""7cec85d7bea7798e"" enable=""false""/> </assemblyBinding> </runtime> </configuration>")); var comparer = DesktopAssemblyIdentityComparer.LoadFromXml(appConfig); compilation = CreateEmptyCompilation( new[] { Parse("") }, references, options: TestOptions.ReleaseDll.WithAssemblyIdentityComparer(comparer)); compilation.VerifyDiagnostics(); } [Fact] public void AppConfig2() { // Create a dll with a reference to .NET system string libSource = @" using System.Runtime.Versioning; public class C { public static FrameworkName Goo() { return null; }}"; var libComp = CreateEmptyCompilation( libSource, references: new[] { MscorlibRef, Net451.System }, options: TestOptions.ReleaseDll); libComp.VerifyDiagnostics(); var refData = libComp.EmitToArray(); var mdRef = MetadataReference.CreateFromImage(refData); var references = new[] { Net451.mscorlib, Net451.System, TestReferences.NetFx.silverlight_v5_0_5_0.System, mdRef }; // Source references the type in the dll string src1 = @"class A { public static void Main(string[] args) { C.Goo(); } }"; var c1 = CreateEmptyCompilation( new[] { Parse(src1) }, references, options: TestOptions.ReleaseDll.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)); c1.VerifyDiagnostics( // error CS1703: Multiple assemblies with equivalent identity have been imported: 'System.dll' and 'System.v5.0.5.0_silverlight.dll'. Remove one of the duplicate references. Diagnostic(ErrorCode.ERR_DuplicateImport).WithArguments("System.dll (net451)", "System.v5.0.5.0_silverlight.dll"), // error CS7069: Reference to type 'System.Runtime.Versioning.FrameworkName' claims it is defined in 'System', but it could not be found Diagnostic(ErrorCode.ERR_MissingTypeInAssembly, "C.Goo").WithArguments( "System.Runtime.Versioning.FrameworkName", "System")); var appConfig = new MemoryStream(Encoding.UTF8.GetBytes( @"<?xml version=""1.0"" encoding=""utf-8"" ?> <configuration> <runtime> <assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1""> <supportPortability PKT=""7cec85d7bea7798e"" enable=""false""/> </assemblyBinding> </runtime> </configuration>")); var comparer = DesktopAssemblyIdentityComparer.LoadFromXml(appConfig); var src2 = @"class A { public static void Main(string[] args) { C.Goo(); } }"; var c2 = CreateEmptyCompilation( new[] { Parse(src2) }, references, options: TestOptions.ReleaseDll.WithAssemblyIdentityComparer(comparer)); c2.VerifyDiagnostics(); } [Fact] [WorkItem(797640, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797640")] public void GetMetadataReferenceAPITest() { var comp = CSharpCompilation.Create("Compilation"); var metadata = Net451.mscorlib; comp = comp.AddReferences(metadata); var assemblySmb = comp.GetReferencedAssemblySymbol(metadata); var reference = comp.GetMetadataReference(assemblySmb); Assert.NotNull(reference); var comp2 = CSharpCompilation.Create("Compilation"); comp2 = comp2.AddReferences(metadata); var reference2 = comp2.GetMetadataReference(assemblySmb); Assert.NotNull(reference2); } [Fact] [WorkItem(40466, "https://github.com/dotnet/roslyn/issues/40466")] public void GetMetadataReference_VisualBasicSymbols() { var comp = CreateCompilation(""); var vbComp = CreateVisualBasicCompilation("", referencedAssemblies: TargetFrameworkUtil.GetReferences(TargetFramework.Standard)); var assembly = (IAssemblySymbol)vbComp.GetBoundReferenceManager().GetReferencedAssemblies().First().Value; Assert.Null(comp.GetMetadataReference(assembly)); Assert.Null(comp.GetMetadataReference(vbComp.Assembly)); Assert.Null(comp.GetMetadataReference((IAssemblySymbol)null)); } [Fact] public void ConsistentParseOptions() { var tree1 = SyntaxFactory.ParseSyntaxTree("", CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6)); var tree2 = SyntaxFactory.ParseSyntaxTree("", CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6)); var tree3 = SyntaxFactory.ParseSyntaxTree("", CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5)); var assemblyName = GetUniqueName(); var compilationOptions = TestOptions.DebugDll; CSharpCompilation.Create(assemblyName, new[] { tree1, tree2 }, new[] { MscorlibRef }, compilationOptions); Assert.Throws<ArgumentException>(() => { CSharpCompilation.Create(assemblyName, new[] { tree1, tree3 }, new[] { MscorlibRef }, compilationOptions); }); } [Fact] public void SubmissionCompilation_Errors() { var genericParameter = typeof(List<>).GetGenericArguments()[0]; var open = typeof(Dictionary<,>).MakeGenericType(typeof(int), genericParameter); var ptr = typeof(int).MakePointerType(); var byref = typeof(int).MakeByRefType(); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", returnType: genericParameter)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", returnType: open)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", returnType: typeof(void))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", returnType: byref)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", globalsType: genericParameter)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", globalsType: open)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", globalsType: typeof(void))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", globalsType: typeof(int))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", globalsType: ptr)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", globalsType: byref)); var s0 = CSharpCompilation.CreateScriptCompilation("a0", globalsType: typeof(List<int>)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a1", previousScriptCompilation: s0, globalsType: typeof(List<bool>))); // invalid options: Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseExe)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.NetModule))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsRuntimeMetadata))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsRuntimeApplication))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsApplication))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithCryptoKeyContainer("goo"))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithCryptoKeyFile("goo.snk"))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithDelaySign(true))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithDelaySign(false))); } [Fact] public void HasSubmissionResult() { Assert.False(CSharpCompilation.CreateScriptCompilation("sub").HasSubmissionResult()); Assert.True(CreateSubmission("1", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.False(CreateSubmission("1;", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.False(CreateSubmission("void goo() { }", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.False(CreateSubmission("using System;", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.False(CreateSubmission("int i;", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.False(CreateSubmission("System.Console.WriteLine();", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.False(CreateSubmission("System.Console.WriteLine()", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.True(CreateSubmission("null", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.True(CreateSubmission("System.Console.WriteLine", parseOptions: TestOptions.Script).HasSubmissionResult()); } /// <summary> /// Previous submission has to have no errors. /// </summary> [Fact] public void PreviousSubmissionWithError() { var s0 = CreateSubmission("int a = \"x\";"); s0.VerifyDiagnostics( // (1,9): error CS0029: Cannot implicitly convert type 'string' to 'int' Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""x""").WithArguments("string", "int")); Assert.Throws<InvalidOperationException>(() => CreateSubmission("a + 1", previous: s0)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateArrayType_DefaultArgs() { var comp = (Compilation)CSharpCompilation.Create(""); var elementType = comp.GetSpecialType(SpecialType.System_Object); var arrayType = comp.CreateArrayTypeSymbol(elementType); Assert.Equal(1, arrayType.Rank); Assert.Equal(CodeAnalysis.NullableAnnotation.None, arrayType.ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, arrayType.ElementType.NullableAnnotation); Assert.Throws<ArgumentException>(() => comp.CreateArrayTypeSymbol(elementType, default)); Assert.Throws<ArgumentException>(() => comp.CreateArrayTypeSymbol(elementType, 0)); arrayType = comp.CreateArrayTypeSymbol(elementType, 1, default); Assert.Equal(1, arrayType.Rank); Assert.Equal(CodeAnalysis.NullableAnnotation.None, arrayType.ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, arrayType.ElementType.NullableAnnotation); Assert.Throws<ArgumentException>(() => comp.CreateArrayTypeSymbol(elementType, rank: default)); Assert.Throws<ArgumentException>(() => comp.CreateArrayTypeSymbol(elementType, rank: 0)); arrayType = comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: default); Assert.Equal(1, arrayType.Rank); Assert.Equal(CodeAnalysis.NullableAnnotation.None, arrayType.ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, arrayType.ElementType.NullableAnnotation); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateArrayType_ElementNullableAnnotation() { var comp = (Compilation)CSharpCompilation.Create(""); var elementType = comp.GetSpecialType(SpecialType.System_Object); Assert.Equal(CodeAnalysis.NullableAnnotation.None, comp.CreateArrayTypeSymbol(elementType).ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, comp.CreateArrayTypeSymbol(elementType).ElementType.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.None).ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.None).ElementType.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.None).ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.None).ElementType.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.NotAnnotated, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.NotAnnotated).ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.NotAnnotated, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.NotAnnotated).ElementType.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.Annotated).ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.Annotated).ElementType.NullableAnnotation); } [Fact] public void CreateAnonymousType_IncorrectLengths() { var compilation = CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)null), ImmutableArray.Create("m1", "m2"))); } [Fact] public void CreateAnonymousType_IncorrectLengths_IsReadOnly() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32), (ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray.Create("m1", "m2"), ImmutableArray.Create(true))); } [Fact] public void CreateAnonymousType_IncorrectLengths_Locations() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32), (ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray.Create("m1", "m2"), memberLocations: ImmutableArray.Create(Location.None))); } [Fact] public void CreateAnonymousType_WritableProperty() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32), (ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray.Create("m1", "m2"), ImmutableArray.Create(false, false))); } [Fact] public void CreateAnonymousType_NullLocations() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentNullException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32), (ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray.Create("m1", "m2"), memberLocations: ImmutableArray.Create(Location.None, null))); } [Fact] public void CreateAnonymousType_NullArgument1() { var compilation = CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentNullException>(() => compilation.CreateAnonymousTypeSymbol( default(ImmutableArray<ITypeSymbol>), ImmutableArray.Create("m1"))); } [Fact] public void CreateAnonymousType_NullArgument2() { var compilation = CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentNullException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)null), default(ImmutableArray<string>))); } [Fact] public void CreateAnonymousType_NullArgument3() { var compilation = CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentNullException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)null), ImmutableArray.Create("m1"))); } [Fact] public void CreateAnonymousType_NullArgument4() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentNullException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray.Create((string)null))); } [Fact] public void CreateAnonymousType1() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); var type = compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create<ITypeSymbol>(compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray.Create("m1")); Assert.True(type.IsAnonymousType); Assert.Equal(1, type.GetMembers().OfType<IPropertySymbol>().Count()); Assert.Equal("<anonymous type: int m1>", type.ToDisplayString()); Assert.All(type.GetMembers().OfType<IPropertySymbol>().Select(p => p.Locations.FirstOrDefault()), loc => Assert.Equal(loc, Location.None)); } [Fact] public void CreateAnonymousType_Locations() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); var tree = CSharpSyntaxTree.ParseText("class C { }"); var loc1 = Location.Create(tree, new TextSpan(0, 1)); var loc2 = Location.Create(tree, new TextSpan(1, 1)); var type = compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create<ITypeSymbol>(compilation.GetSpecialType(SpecialType.System_Int32), compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray.Create("m1", "m2"), memberLocations: ImmutableArray.Create(loc1, loc2)); Assert.True(type.IsAnonymousType); Assert.Equal(2, type.GetMembers().OfType<IPropertySymbol>().Count()); Assert.Equal(loc1, type.GetMembers("m1").Single().Locations.Single()); Assert.Equal(loc2, type.GetMembers("m2").Single().Locations.Single()); Assert.Equal("<anonymous type: int m1, int m2>", type.ToDisplayString()); } [Fact] public void CreateAnonymousType2() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); var type = compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create<ITypeSymbol>(compilation.GetSpecialType(SpecialType.System_Int32), compilation.GetSpecialType(SpecialType.System_Boolean)), ImmutableArray.Create("m1", "m2")); Assert.True(type.IsAnonymousType); Assert.Equal(2, type.GetMembers().OfType<IPropertySymbol>().Count()); Assert.Equal("<anonymous type: int m1, bool m2>", type.ToDisplayString()); Assert.All(type.GetMembers().OfType<IPropertySymbol>().Select(p => p.Locations.FirstOrDefault()), loc => Assert.Equal(loc, Location.None)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateAnonymousType_DefaultArgs() { var comp = (Compilation)CSharpCompilation.Create(""); var memberTypes = ImmutableArray.Create<ITypeSymbol>(comp.GetSpecialType(SpecialType.System_Object), comp.GetSpecialType(SpecialType.System_String)); var memberNames = ImmutableArray.Create("P", "Q"); var type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, default); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, default, default); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, default, default, default); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, memberIsReadOnly: default); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, memberLocations: default); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, memberNullableAnnotations: default); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateAnonymousType_MemberNullableAnnotations_Empty() { var comp = (Compilation)CSharpCompilation.Create(""); var type = comp.CreateAnonymousTypeSymbol(ImmutableArray<ITypeSymbol>.Empty, ImmutableArray<string>.Empty, memberNullableAnnotations: ImmutableArray<CodeAnalysis.NullableAnnotation>.Empty); Assert.Equal("<empty anonymous type>", type.ToTestDisplayString(includeNonNullable: true)); AssertEx.Equal(Array.Empty<CodeAnalysis.NullableAnnotation>(), GetAnonymousTypeNullableAnnotations(type)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateAnonymousType_MemberNullableAnnotations() { var comp = (Compilation)CSharpCompilation.Create(""); var memberTypes = ImmutableArray.Create<ITypeSymbol>(comp.GetSpecialType(SpecialType.System_Object), comp.GetSpecialType(SpecialType.System_String)); var memberNames = ImmutableArray.Create("P", "Q"); var type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.None, CodeAnalysis.NullableAnnotation.None }, GetAnonymousTypeNullableAnnotations(type)); Assert.Throws<ArgumentException>(() => comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, memberNullableAnnotations: ImmutableArray.Create(CodeAnalysis.NullableAnnotation.NotAnnotated))); type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, memberNullableAnnotations: ImmutableArray.Create(CodeAnalysis.NullableAnnotation.NotAnnotated, CodeAnalysis.NullableAnnotation.Annotated)); Assert.Equal("<anonymous type: System.Object! P, System.String? Q>", type.ToTestDisplayString(includeNonNullable: true)); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.NotAnnotated, CodeAnalysis.NullableAnnotation.Annotated }, GetAnonymousTypeNullableAnnotations(type)); } private static ImmutableArray<CodeAnalysis.NullableAnnotation> GetAnonymousTypeNullableAnnotations(ITypeSymbol type) { return type.GetMembers().OfType<IPropertySymbol>().SelectAsArray(p => { var result = p.Type.NullableAnnotation; Assert.Equal(result, p.NullableAnnotation); return result; }); } [Fact] [WorkItem(36046, "https://github.com/dotnet/roslyn/issues/36046")] public void ConstructTypeWithNullability() { var source = @"class Pair<T, U> { }"; var comp = (Compilation)CreateCompilation(source); var genericType = (INamedTypeSymbol)comp.GetMember("Pair"); var typeArguments = ImmutableArray.Create<ITypeSymbol>(comp.GetSpecialType(SpecialType.System_Object), comp.GetSpecialType(SpecialType.System_String)); Assert.Throws<ArgumentException>(() => genericType.Construct(default(ImmutableArray<ITypeSymbol>), default(ImmutableArray<CodeAnalysis.NullableAnnotation>))); Assert.Throws<ArgumentException>(() => genericType.Construct(typeArguments: default, typeArgumentNullableAnnotations: default)); var type = genericType.Construct(typeArguments, default); Assert.Equal("Pair<System.Object, System.String>", type.ToTestDisplayString(includeNonNullable: true)); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.None, CodeAnalysis.NullableAnnotation.None }, type.TypeArgumentNullableAnnotations); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.None, CodeAnalysis.NullableAnnotation.None }, type.TypeArgumentNullableAnnotations()); Assert.Throws<ArgumentException>(() => genericType.Construct(typeArguments, ImmutableArray<CodeAnalysis.NullableAnnotation>.Empty)); Assert.Throws<ArgumentException>(() => genericType.Construct(ImmutableArray.Create<ITypeSymbol>(null, null), default)); type = genericType.Construct(typeArguments, ImmutableArray.Create(CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.NotAnnotated)); Assert.Equal("Pair<System.Object?, System.String!>", type.ToTestDisplayString(includeNonNullable: true)); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.NotAnnotated }, type.TypeArgumentNullableAnnotations); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.NotAnnotated }, type.TypeArgumentNullableAnnotations()); // Type arguments from VB. comp = CreateVisualBasicCompilation(""); typeArguments = ImmutableArray.Create<ITypeSymbol>(comp.GetSpecialType(SpecialType.System_Object), comp.GetSpecialType(SpecialType.System_String)); Assert.Throws<ArgumentException>(() => genericType.Construct(typeArguments, default)); } [Fact] [WorkItem(37310, "https://github.com/dotnet/roslyn/issues/37310")] public void ConstructMethodWithNullability() { var source = @"class Program { static void M<T, U>() { } }"; var comp = (Compilation)CreateCompilation(source); var genericMethod = (IMethodSymbol)comp.GetMember("Program.M"); var typeArguments = ImmutableArray.Create<ITypeSymbol>(comp.GetSpecialType(SpecialType.System_Object), comp.GetSpecialType(SpecialType.System_String)); Assert.Throws<ArgumentException>(() => genericMethod.Construct(default(ImmutableArray<ITypeSymbol>), default(ImmutableArray<CodeAnalysis.NullableAnnotation>))); Assert.Throws<ArgumentException>(() => genericMethod.Construct(typeArguments: default, typeArgumentNullableAnnotations: default)); var type = genericMethod.Construct(typeArguments, default); Assert.Equal("void Program.M<System.Object, System.String>()", type.ToTestDisplayString(includeNonNullable: true)); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.None, CodeAnalysis.NullableAnnotation.None }, type.TypeArgumentNullableAnnotations); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.None, CodeAnalysis.NullableAnnotation.None }, type.TypeArgumentNullableAnnotations()); Assert.Throws<ArgumentException>(() => genericMethod.Construct(typeArguments, ImmutableArray<CodeAnalysis.NullableAnnotation>.Empty)); Assert.Throws<ArgumentException>(() => genericMethod.Construct(ImmutableArray.Create<ITypeSymbol>(null, null), default)); type = genericMethod.Construct(typeArguments, ImmutableArray.Create(CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.NotAnnotated)); Assert.Equal("void Program.M<System.Object?, System.String!>()", type.ToTestDisplayString(includeNonNullable: true)); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.NotAnnotated }, type.TypeArgumentNullableAnnotations); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.NotAnnotated }, type.TypeArgumentNullableAnnotations()); // Type arguments from VB. comp = CreateVisualBasicCompilation(""); typeArguments = ImmutableArray.Create<ITypeSymbol>(comp.GetSpecialType(SpecialType.System_Object), comp.GetSpecialType(SpecialType.System_String)); Assert.Throws<ArgumentException>(() => genericMethod.Construct(typeArguments, default)); } #region Script return values [ConditionalFact(typeof(DesktopOnly))] public void ReturnNullAsObject() { var script = CreateSubmission("return null;", returnType: typeof(object)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnStringAsObject() { var script = CreateSubmission("return \"¡Hola!\";", returnType: typeof(object)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnIntAsObject() { var script = CreateSubmission("return 42;", returnType: typeof(object)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void TrailingReturnVoidAsObject() { var script = CreateSubmission("return", returnType: typeof(object)); script.VerifyDiagnostics( // (1,7): error CS1733: Expected expression // return Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(1, 7), // (1,7): error CS1002: ; expected // return Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 7)); Assert.False(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnIntAsInt() { var script = CreateSubmission("return 42;", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnNullResultType() { // test that passing null is the same as passing typeof(object) var script = CreateSubmission("return 42;", returnType: null); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnNoSemicolon() { var script = CreateSubmission("return 42", returnType: typeof(uint)); script.VerifyDiagnostics( // (1,10): error CS1002: ; expected // return 42 Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 10)); Assert.False(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnAwait() { var script = CreateSubmission("return await System.Threading.Tasks.Task.FromResult(42);", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); script = CreateSubmission("return await System.Threading.Tasks.Task.FromResult(42);", returnType: typeof(Task<int>)); script.VerifyDiagnostics( // (1,8): error CS0029: Cannot implicitly convert type 'int' to 'System.Threading.Tasks.Task<int>' // return await System.Threading.Tasks.Task.FromResult(42); Diagnostic(ErrorCode.ERR_NoImplicitConv, "await System.Threading.Tasks.Task.FromResult(42)").WithArguments("int", "System.Threading.Tasks.Task<int>").WithLocation(1, 8)); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnTaskNoAwait() { var script = CreateSubmission("return System.Threading.Tasks.Task.FromResult(42);", returnType: typeof(int)); script.VerifyDiagnostics( // (1,8): error CS4016: Since this is an async method, the return expression must be of type 'int' rather than 'Task<int>' // return System.Threading.Tasks.Task.FromResult(42); Diagnostic(ErrorCode.ERR_BadAsyncReturnExpression, "System.Threading.Tasks.Task.FromResult(42)").WithArguments("int").WithLocation(1, 8)); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnInNestedScopes() { var script = CreateSubmission(@" bool condition = false; if (condition) { return 1; } else { return -1; }", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnInNestedScopeWithTrailingExpression() { var script = CreateSubmission(@" if (true) { return 1; } System.Console.WriteLine();", returnType: typeof(object)); script.VerifyDiagnostics( // (6,1): warning CS0162: Unreachable code detected // System.Console.WriteLine(); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(6, 1)); Assert.True(script.HasSubmissionResult()); script = CreateSubmission(@" if (true) { return 1; } System.Console.WriteLine()", returnType: typeof(object)); script.VerifyDiagnostics( // (6,1): warning CS0162: Unreachable code detected // System.Console.WriteLine(); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(6, 1)); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnInNestedScopeNoTrailingExpression() { var script = CreateSubmission(@" bool condition = false; if (condition) { return 1; } System.Console.WriteLine();", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnInNestedMethod() { var script = CreateSubmission(@" int TopMethod() { return 42; }", returnType: typeof(string)); script.VerifyDiagnostics(); Assert.False(script.HasSubmissionResult()); script = CreateSubmission(@" object TopMethod() { return new System.Exception(); } TopMethod().ToString()", returnType: typeof(string)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnInNestedLambda() { var script = CreateSubmission(@" System.Func<object> f = () => { return new System.Exception(); }; 42", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); script = CreateSubmission(@" System.Func<object> f = () => new System.Exception(); 42", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnInNestedAnonymousMethod() { var script = CreateSubmission(@" System.Func<object> f = delegate () { return new System.Exception(); }; 42", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void LoadedFileWithWrongReturnType() { var resolver = TestSourceReferenceResolver.Create( KeyValuePairUtil.Create("a.csx", "return \"Who returns a string?\";")); var script = CreateSubmission(@" #load ""a.csx"" 42", returnType: typeof(int), options: TestOptions.DebugDll.WithSourceReferenceResolver(resolver)); script.VerifyDiagnostics( // a.csx(1,8): error CS0029: Cannot implicitly convert type 'string' to 'int' // return "Who returns a string?" Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""Who returns a string?""").WithArguments("string", "int").WithLocation(1, 8), // (3,1): warning CS0162: Unreachable code detected // 42 Diagnostic(ErrorCode.WRN_UnreachableCode, "42").WithLocation(3, 1)); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnVoidInNestedMethodOrLambda() { var script = CreateSubmission(@" void M1() { return; } System.Action a = () => { return; }; 42", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); var compilation = CreateCompilationWithMscorlib45(@" void M1() { return; } System.Action a = () => { return; }; 42", parseOptions: TestOptions.Script); compilation.VerifyDiagnostics(); } #endregion } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/MemberInfo/ConstructorInfoImpl.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using Microsoft.VisualStudio.Debugger.Metadata; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal sealed class ConstructorInfoImpl : ConstructorInfo { internal readonly System.Reflection.ConstructorInfo Constructor; internal ConstructorInfoImpl(System.Reflection.ConstructorInfo constructor) { Debug.Assert(constructor != null); this.Constructor = constructor; } public override System.Reflection.MethodAttributes Attributes { get { throw new NotImplementedException(); } } public override System.Reflection.CallingConventions CallingConvention { get { throw new NotImplementedException(); } } public override Type DeclaringType { get { return (TypeImpl)Constructor.DeclaringType; } } public override bool IsEquivalentTo(MemberInfo other) { throw new NotImplementedException(); } public override bool IsGenericMethodDefinition { get { throw new NotImplementedException(); } } public override MemberTypes MemberType { get { return (MemberTypes)Constructor.MemberType; } } public override int MetadataToken { get { throw new NotImplementedException(); } } public override RuntimeMethodHandle MethodHandle { get { throw new NotImplementedException(); } } public override Microsoft.VisualStudio.Debugger.Metadata.Module Module { get { throw new NotImplementedException(); } } public override string Name { get { return Constructor.Name; } } public override Type ReflectedType { get { throw new NotImplementedException(); } } public override object[] GetCustomAttributes(bool inherit) { throw new NotImplementedException(); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotImplementedException(); } public override IList<Microsoft.VisualStudio.Debugger.Metadata.CustomAttributeData> GetCustomAttributesData() { throw new NotImplementedException(); } public override Microsoft.VisualStudio.Debugger.Metadata.MethodBody GetMethodBody() { throw new NotImplementedException(); } public override System.Reflection.MethodImplAttributes GetMethodImplementationFlags() { throw new NotImplementedException(); } public override Microsoft.VisualStudio.Debugger.Metadata.ParameterInfo[] GetParameters() { throw new NotImplementedException(); } public override object Invoke(BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) { Debug.Assert(binder == null, "NYI"); return Constructor.Invoke((System.Reflection.BindingFlags)invokeAttr, null, parameters, culture); } public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) { throw new NotImplementedException(); } public override bool IsDefined(Type attributeType, bool inherit) { throw new NotImplementedException(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using Microsoft.VisualStudio.Debugger.Metadata; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal sealed class ConstructorInfoImpl : ConstructorInfo { internal readonly System.Reflection.ConstructorInfo Constructor; internal ConstructorInfoImpl(System.Reflection.ConstructorInfo constructor) { Debug.Assert(constructor != null); this.Constructor = constructor; } public override System.Reflection.MethodAttributes Attributes { get { throw new NotImplementedException(); } } public override System.Reflection.CallingConventions CallingConvention { get { throw new NotImplementedException(); } } public override Type DeclaringType { get { return (TypeImpl)Constructor.DeclaringType; } } public override bool IsEquivalentTo(MemberInfo other) { throw new NotImplementedException(); } public override bool IsGenericMethodDefinition { get { throw new NotImplementedException(); } } public override MemberTypes MemberType { get { return (MemberTypes)Constructor.MemberType; } } public override int MetadataToken { get { throw new NotImplementedException(); } } public override RuntimeMethodHandle MethodHandle { get { throw new NotImplementedException(); } } public override Microsoft.VisualStudio.Debugger.Metadata.Module Module { get { throw new NotImplementedException(); } } public override string Name { get { return Constructor.Name; } } public override Type ReflectedType { get { throw new NotImplementedException(); } } public override object[] GetCustomAttributes(bool inherit) { throw new NotImplementedException(); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotImplementedException(); } public override IList<Microsoft.VisualStudio.Debugger.Metadata.CustomAttributeData> GetCustomAttributesData() { throw new NotImplementedException(); } public override Microsoft.VisualStudio.Debugger.Metadata.MethodBody GetMethodBody() { throw new NotImplementedException(); } public override System.Reflection.MethodImplAttributes GetMethodImplementationFlags() { throw new NotImplementedException(); } public override Microsoft.VisualStudio.Debugger.Metadata.ParameterInfo[] GetParameters() { throw new NotImplementedException(); } public override object Invoke(BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) { Debug.Assert(binder == null, "NYI"); return Constructor.Invoke((System.Reflection.BindingFlags)invokeAttr, null, parameters, culture); } public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) { throw new NotImplementedException(); } public override bool IsDefined(Type attributeType, bool inherit) { throw new NotImplementedException(); } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/InheritanceMargin/InheritanceRelationship.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; namespace Microsoft.CodeAnalysis.InheritanceMargin { /// <summary> /// Indicate the relationship between the member and its inheritance target /// </summary> [Flags] internal enum InheritanceRelationship { /// <summary> /// A default case that should not be used. /// </summary> None = 0, /// <summary> /// Implented interfaces for class or struct. Shown as I↑ /// </summary> ImplementedInterface = 1, /// <summary> /// Base type for class or struct. Shown as O↑ /// </summary> BaseType = 2, /// <summary> /// Derived type for class or struct. Shown as O↓ /// </summary> DerivedType = 4, /// <summary> /// Inherited interface for interface. Shown as I↑ /// </summary> InheritedInterface = 8, /// <summary> /// Implementing class, struct and interface for interface. Shown as I↓ /// </summary> ImplementingType = 16, /// <summary> /// Implemented member for member in class or structure. Shown as I↑ /// </summary> ImplementedMember = 32, /// <summary> /// Overridden member for member in class or structure. Shown as O↑ /// </summary> OverriddenMember = 64, /// <summary> /// Overrrding member for member in class or structure. Shown as O↓ /// </summary> OverridingMember = 128, /// <summary> /// Implmenting member for member in interface. Shown as I↓ /// </summary> ImplementingMember = 256 } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis.InheritanceMargin { /// <summary> /// Indicate the relationship between the member and its inheritance target /// </summary> [Flags] internal enum InheritanceRelationship { /// <summary> /// A default case that should not be used. /// </summary> None = 0, /// <summary> /// Implented interfaces for class or struct. Shown as I↑ /// </summary> ImplementedInterface = 1, /// <summary> /// Base type for class or struct. Shown as O↑ /// </summary> BaseType = 2, /// <summary> /// Derived type for class or struct. Shown as O↓ /// </summary> DerivedType = 4, /// <summary> /// Inherited interface for interface. Shown as I↑ /// </summary> InheritedInterface = 8, /// <summary> /// Implementing class, struct and interface for interface. Shown as I↓ /// </summary> ImplementingType = 16, /// <summary> /// Implemented member for member in class or structure. Shown as I↑ /// </summary> ImplementedMember = 32, /// <summary> /// Overridden member for member in class or structure. Shown as O↑ /// </summary> OverriddenMember = 64, /// <summary> /// Overrrding member for member in class or structure. Shown as O↓ /// </summary> OverridingMember = 128, /// <summary> /// Implmenting member for member in interface. Shown as I↓ /// </summary> ImplementingMember = 256 } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Test/Symbol/DeclarationTests.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 System.Text; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; //test namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DeclarationTests : CSharpTestBase { private CompilationUnitSyntax ParseFile(string text) { return SyntaxFactory.ParseCompilationUnit(text); } [Fact] public void TestSimpleDeclarations() { var text1 = @" namespace NA.NB { partial class C<T> { partial class D { int F; } } class C { } } "; var text2 = @" namespace NA { namespace NB { partial class C<T> { partial class D { void G() {}; } } } } "; var tree1 = SyntaxFactory.ParseSyntaxTree(text1); var tree2 = SyntaxFactory.ParseSyntaxTree(text2); Assert.NotNull(tree1); Assert.NotNull(tree2); var decl1 = DeclarationTreeBuilder.ForTree(tree1, TestOptions.DebugExe.ScriptClassName, isSubmission: false); var decl2 = DeclarationTreeBuilder.ForTree(tree2, TestOptions.DebugExe.ScriptClassName, isSubmission: false); Assert.NotNull(decl1); Assert.NotNull(decl2); Assert.Equal(string.Empty, decl1.Name); Assert.Equal(string.Empty, decl2.Name); Assert.Equal(1, decl1.Children.Length); Assert.Equal(1, decl2.Children.Length); var na1 = decl1.Children.Single(); var na2 = decl2.Children.Single(); Assert.NotNull(na1); Assert.NotNull(na2); Assert.Equal(DeclarationKind.Namespace, na1.Kind); Assert.Equal(DeclarationKind.Namespace, na2.Kind); Assert.Equal("NA", na1.Name); Assert.Equal("NA", na2.Name); Assert.Equal(1, na1.Children.Length); Assert.Equal(1, na2.Children.Length); var nb1 = na1.Children.Single(); var nb2 = na2.Children.Single(); Assert.NotNull(nb1); Assert.NotNull(nb2); Assert.Equal(DeclarationKind.Namespace, nb1.Kind); Assert.Equal(DeclarationKind.Namespace, nb2.Kind); Assert.Equal("NB", nb1.Name); Assert.Equal("NB", nb2.Name); Assert.Equal(2, nb1.Children.Length); Assert.Equal(1, nb2.Children.Length); var ct1 = (SingleTypeDeclaration)nb1.Children.First(); var ct2 = (SingleTypeDeclaration)nb2.Children.Single(); Assert.Equal(DeclarationKind.Class, ct1.Kind); Assert.Equal(DeclarationKind.Class, ct2.Kind); Assert.NotNull(ct1); Assert.NotNull(ct2); Assert.Equal("C", ct1.Name); Assert.Equal("C", ct2.Name); Assert.Equal(1, ct1.Arity); Assert.Equal(1, ct2.Arity); Assert.Equal(1, ct1.Children.Length); Assert.Equal(1, ct2.Children.Length); var c1 = (SingleTypeDeclaration)nb1.Children.Skip(1).Single(); Assert.NotNull(c1); Assert.Equal(DeclarationKind.Class, c1.Kind); Assert.Equal("C", c1.Name); Assert.Equal(0, c1.Arity); var d1 = ct1.Children.Single(); var d2 = ct2.Children.Single(); Assert.NotNull(d1); Assert.NotNull(d2); Assert.Equal(DeclarationKind.Class, d1.Kind); Assert.Equal(DeclarationKind.Class, d2.Kind); Assert.Equal("D", d1.Name); Assert.Equal("D", d2.Name); Assert.Equal(0, d1.Arity); Assert.Equal(0, d2.Arity); Assert.Equal(0, d1.Children.Length); Assert.Equal(0, d2.Children.Length); var table = DeclarationTable.Empty; var mr = table.CalculateMergedRoot(null); Assert.NotNull(mr); Assert.True(mr.Declarations.IsEmpty); Assert.True(table.TypeNames.IsEmpty()); table = table.AddRootDeclaration(Lazy(decl1)); mr = table.CalculateMergedRoot(null); Assert.Equal(mr.Declarations, new[] { decl1 }); Assert.True(table.TypeNames.OrderBy(s => s).SequenceEqual(new[] { "C", "D" })); Assert.Equal(DeclarationKind.Namespace, mr.Kind); Assert.Equal(string.Empty, mr.Name); var na = mr.Children.Single(); Assert.Equal(DeclarationKind.Namespace, na.Kind); Assert.Equal("NA", na.Name); var nb = na.Children.Single(); Assert.Equal(DeclarationKind.Namespace, nb.Kind); Assert.Equal("NB", nb.Name); var ct = nb.Children.OfType<MergedTypeDeclaration>().Single(x => x.Arity == 1); Assert.Equal(1, ct.Arity); Assert.Equal(DeclarationKind.Class, ct.Kind); Assert.Equal("C", ct.Name); var c = nb.Children.OfType<MergedTypeDeclaration>().Single(x => x.Arity == 0); Assert.Equal(0, c.Arity); Assert.Equal(DeclarationKind.Class, c.Kind); Assert.Equal("C", c.Name); var d = ct.Children.Single(); Assert.Equal(0, d.Arity); Assert.Equal(DeclarationKind.Class, d.Kind); Assert.Equal("D", d.Name); table = table.AddRootDeclaration(Lazy(decl2)); mr = table.CalculateMergedRoot(null); Assert.True(table.TypeNames.Distinct().OrderBy(s => s).SequenceEqual(new[] { "C", "D" })); Assert.Equal(mr.Declarations, new[] { decl1, decl2 }); Assert.Equal(DeclarationKind.Namespace, mr.Kind); Assert.Equal(string.Empty, mr.Name); na = mr.Children.Single(); Assert.Equal(DeclarationKind.Namespace, na.Kind); Assert.Equal("NA", na.Name); nb = na.Children.Single(); Assert.Equal(DeclarationKind.Namespace, nb.Kind); Assert.Equal("NB", nb.Name); ct = nb.Children.OfType<MergedTypeDeclaration>().Single(x => x.Arity == 1); Assert.Equal(1, ct.Arity); Assert.Equal(DeclarationKind.Class, ct.Kind); Assert.Equal("C", ct.Name); c = nb.Children.OfType<MergedTypeDeclaration>().Single(x => x.Arity == 0); Assert.Equal(0, c.Arity); Assert.Equal(DeclarationKind.Class, c.Kind); Assert.Equal("C", c.Name); d = ct.Children.Single(); Assert.Equal(0, d.Arity); Assert.Equal(DeclarationKind.Class, d.Kind); Assert.Equal("D", d.Name); } private Lazy<RootSingleNamespaceDeclaration> Lazy(RootSingleNamespaceDeclaration decl) { return new Lazy<RootSingleNamespaceDeclaration>(() => decl); } [Fact] public void TestTypeNames() { var text1 = @" namespace NA.NB { partial class A<T> { partial class B { int F; } } } "; var text2 = @" namespace NA { namespace NB { partial class C<T> { partial class D { void G() {}; } } } } "; var tree1 = SyntaxFactory.ParseSyntaxTree(text1); var tree2 = SyntaxFactory.ParseSyntaxTree(text2); Assert.NotNull(tree1); Assert.NotNull(tree2); var decl1 = Lazy(DeclarationTreeBuilder.ForTree(tree1, TestOptions.DebugExe.ScriptClassName, isSubmission: false)); var decl2 = Lazy(DeclarationTreeBuilder.ForTree(tree2, TestOptions.DebugExe.ScriptClassName, isSubmission: false)); var table = DeclarationTable.Empty; table = table.AddRootDeclaration(decl1); Assert.True(table.TypeNames.OrderBy(s => s).SequenceEqual(new[] { "A", "B" })); table = table.AddRootDeclaration(decl2); Assert.True(table.TypeNames.OrderBy(s => s).SequenceEqual(new[] { "A", "B", "C", "D" })); table = table.RemoveRootDeclaration(decl2); Assert.True(table.TypeNames.OrderBy(s => s).SequenceEqual(new[] { "A", "B" })); table = table.AddRootDeclaration(decl2); Assert.True(table.TypeNames.OrderBy(s => s).SequenceEqual(new[] { "A", "B", "C", "D" })); table = table.RemoveRootDeclaration(decl1); Assert.True(table.TypeNames.OrderBy(s => s).SequenceEqual(new[] { "C", "D" })); table = table.RemoveRootDeclaration(decl2); Assert.True(table.TypeNames.IsEmpty()); } [Fact] public void Bug2038() { string code = @" public public interface testiface {}"; var comp = CSharpCompilation.Create( "Test.dll", new[] { SyntaxFactory.ParseSyntaxTree(code) }, options: TestOptions.ReleaseDll); Assert.Equal(SymbolKind.NamedType, comp.GlobalNamespace.GetMembers()[0].Kind); } [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation))] public void OnlyOneParse() { var underlyingTree = SyntaxFactory.ParseSyntaxTree(@" using System; class C { public B X(B b) { return b; } C(){} } "); var foreignType = SyntaxFactory.ParseSyntaxTree(@" public class B { public int member(string s) { return s.Length; } B(){} } "); var countedTree = new CountedSyntaxTree(foreignType); var compilation = CreateCompilation(new SyntaxTree[] { underlyingTree, countedTree }, skipUsesIsNullable: true, options: TestOptions.ReleaseDll); var type = compilation.Assembly.GlobalNamespace.GetTypeMembers().First(); Assert.Equal(1, countedTree.AccessCount); // parse once to build the decl table // We shouldn't need to go back to syntax to get info about the member names. var memberNames = type.MemberNames; Assert.Equal(1, countedTree.AccessCount); // Getting the interfaces will cause us to do some more binding of the current type. var interfaces = type.Interfaces(); Assert.Equal(1, countedTree.AccessCount); // Now bind the members. var method = (MethodSymbol)type.GetMembers().First(); Assert.Equal(1, countedTree.AccessCount); // Once we have the method, we shouldn't need to go back to syntax again. var returnType = method.ReturnTypeWithAnnotations; Assert.Equal(1, countedTree.AccessCount); var parameterType = method.Parameters.Single(); Assert.Equal(1, countedTree.AccessCount); } /// <remarks> /// When using this type, make sure to pass an explicit CompilationOptions to CreateCompilation, as the check /// to see whether the syntax tree has top-level statements will increment the counter. /// </remarks> private class CountedSyntaxTree : CSharpSyntaxTree { private class Reference : SyntaxReference { private readonly CountedSyntaxTree _countedSyntaxTree; private readonly SyntaxReference _underlyingSyntaxReference; public Reference(CountedSyntaxTree countedSyntaxTree, SyntaxReference syntaxReference) { _countedSyntaxTree = countedSyntaxTree; _underlyingSyntaxReference = syntaxReference; } public override SyntaxTree SyntaxTree { get { return _countedSyntaxTree; } } public override TextSpan Span { get { return _underlyingSyntaxReference.Span; } } public override SyntaxNode GetSyntax(CancellationToken cancellationToken) { // Note: It's important for us to maintain identity of nodes/trees, so we find // the equivalent node in our CountedSyntaxTree. _countedSyntaxTree.AccessCount++; var nodeInUnderlying = _underlyingSyntaxReference.GetSyntax(cancellationToken); var token = _countedSyntaxTree.GetCompilationUnitRoot(cancellationToken).FindToken(nodeInUnderlying.SpanStart); for (var node = token.Parent; node != null; node = node.Parent) { if (node.Span == nodeInUnderlying.Span && node.RawKind == nodeInUnderlying.RawKind) { return (CSharpSyntaxNode)node; } } throw new Exception("Should have found the node"); } } private readonly SyntaxTree _underlyingTree; private readonly CompilationUnitSyntax _root; public int AccessCount; public CountedSyntaxTree(SyntaxTree underlying) { Debug.Assert(underlying != null); Debug.Assert(underlying.HasCompilationUnitRoot); _underlyingTree = underlying; _root = CloneNodeAsRoot(_underlyingTree.GetCompilationUnitRoot(CancellationToken.None)); } public override string FilePath { get { return _underlyingTree.FilePath; } } public override CSharpParseOptions Options { get { return (CSharpParseOptions)_underlyingTree.Options; } } public override CSharpSyntaxNode GetRoot(CancellationToken cancellationToken = default(CancellationToken)) { AccessCount++; return _root; } public override bool TryGetRoot(out CSharpSyntaxNode root) { root = _root; AccessCount++; return true; } public override bool HasCompilationUnitRoot { get { return true; } } public override SourceText GetText(CancellationToken cancellationToken) { return _underlyingTree.GetText(cancellationToken); } public override bool TryGetText(out SourceText text) { return _underlyingTree.TryGetText(out text); } public override Encoding Encoding { get { return _underlyingTree.Encoding; } } public override int Length { get { return _underlyingTree.Length; } } [Obsolete] public override ImmutableDictionary<string, ReportDiagnostic> DiagnosticOptions => throw new NotImplementedException(); public override SyntaxReference GetReference(SyntaxNode node) { return new Reference(this, _underlyingTree.GetReference(node)); } public override SyntaxTree WithChangedText(SourceText newText) { return _underlyingTree.WithChangedText(newText); } public override SyntaxTree WithRootAndOptions(SyntaxNode root, ParseOptions options) { throw new NotImplementedException(); } public override SyntaxTree WithFilePath(string path) { throw new NotImplementedException(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; //test namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DeclarationTests : CSharpTestBase { private CompilationUnitSyntax ParseFile(string text) { return SyntaxFactory.ParseCompilationUnit(text); } [Fact] public void TestSimpleDeclarations() { var text1 = @" namespace NA.NB { partial class C<T> { partial class D { int F; } } class C { } } "; var text2 = @" namespace NA { namespace NB { partial class C<T> { partial class D { void G() {}; } } } } "; var tree1 = SyntaxFactory.ParseSyntaxTree(text1); var tree2 = SyntaxFactory.ParseSyntaxTree(text2); Assert.NotNull(tree1); Assert.NotNull(tree2); var decl1 = DeclarationTreeBuilder.ForTree(tree1, TestOptions.DebugExe.ScriptClassName, isSubmission: false); var decl2 = DeclarationTreeBuilder.ForTree(tree2, TestOptions.DebugExe.ScriptClassName, isSubmission: false); Assert.NotNull(decl1); Assert.NotNull(decl2); Assert.Equal(string.Empty, decl1.Name); Assert.Equal(string.Empty, decl2.Name); Assert.Equal(1, decl1.Children.Length); Assert.Equal(1, decl2.Children.Length); var na1 = decl1.Children.Single(); var na2 = decl2.Children.Single(); Assert.NotNull(na1); Assert.NotNull(na2); Assert.Equal(DeclarationKind.Namespace, na1.Kind); Assert.Equal(DeclarationKind.Namespace, na2.Kind); Assert.Equal("NA", na1.Name); Assert.Equal("NA", na2.Name); Assert.Equal(1, na1.Children.Length); Assert.Equal(1, na2.Children.Length); var nb1 = na1.Children.Single(); var nb2 = na2.Children.Single(); Assert.NotNull(nb1); Assert.NotNull(nb2); Assert.Equal(DeclarationKind.Namespace, nb1.Kind); Assert.Equal(DeclarationKind.Namespace, nb2.Kind); Assert.Equal("NB", nb1.Name); Assert.Equal("NB", nb2.Name); Assert.Equal(2, nb1.Children.Length); Assert.Equal(1, nb2.Children.Length); var ct1 = (SingleTypeDeclaration)nb1.Children.First(); var ct2 = (SingleTypeDeclaration)nb2.Children.Single(); Assert.Equal(DeclarationKind.Class, ct1.Kind); Assert.Equal(DeclarationKind.Class, ct2.Kind); Assert.NotNull(ct1); Assert.NotNull(ct2); Assert.Equal("C", ct1.Name); Assert.Equal("C", ct2.Name); Assert.Equal(1, ct1.Arity); Assert.Equal(1, ct2.Arity); Assert.Equal(1, ct1.Children.Length); Assert.Equal(1, ct2.Children.Length); var c1 = (SingleTypeDeclaration)nb1.Children.Skip(1).Single(); Assert.NotNull(c1); Assert.Equal(DeclarationKind.Class, c1.Kind); Assert.Equal("C", c1.Name); Assert.Equal(0, c1.Arity); var d1 = ct1.Children.Single(); var d2 = ct2.Children.Single(); Assert.NotNull(d1); Assert.NotNull(d2); Assert.Equal(DeclarationKind.Class, d1.Kind); Assert.Equal(DeclarationKind.Class, d2.Kind); Assert.Equal("D", d1.Name); Assert.Equal("D", d2.Name); Assert.Equal(0, d1.Arity); Assert.Equal(0, d2.Arity); Assert.Equal(0, d1.Children.Length); Assert.Equal(0, d2.Children.Length); var table = DeclarationTable.Empty; var mr = table.CalculateMergedRoot(null); Assert.NotNull(mr); Assert.True(mr.Declarations.IsEmpty); Assert.True(table.TypeNames.IsEmpty()); table = table.AddRootDeclaration(Lazy(decl1)); mr = table.CalculateMergedRoot(null); Assert.Equal(mr.Declarations, new[] { decl1 }); Assert.True(table.TypeNames.OrderBy(s => s).SequenceEqual(new[] { "C", "D" })); Assert.Equal(DeclarationKind.Namespace, mr.Kind); Assert.Equal(string.Empty, mr.Name); var na = mr.Children.Single(); Assert.Equal(DeclarationKind.Namespace, na.Kind); Assert.Equal("NA", na.Name); var nb = na.Children.Single(); Assert.Equal(DeclarationKind.Namespace, nb.Kind); Assert.Equal("NB", nb.Name); var ct = nb.Children.OfType<MergedTypeDeclaration>().Single(x => x.Arity == 1); Assert.Equal(1, ct.Arity); Assert.Equal(DeclarationKind.Class, ct.Kind); Assert.Equal("C", ct.Name); var c = nb.Children.OfType<MergedTypeDeclaration>().Single(x => x.Arity == 0); Assert.Equal(0, c.Arity); Assert.Equal(DeclarationKind.Class, c.Kind); Assert.Equal("C", c.Name); var d = ct.Children.Single(); Assert.Equal(0, d.Arity); Assert.Equal(DeclarationKind.Class, d.Kind); Assert.Equal("D", d.Name); table = table.AddRootDeclaration(Lazy(decl2)); mr = table.CalculateMergedRoot(null); Assert.True(table.TypeNames.Distinct().OrderBy(s => s).SequenceEqual(new[] { "C", "D" })); Assert.Equal(mr.Declarations, new[] { decl1, decl2 }); Assert.Equal(DeclarationKind.Namespace, mr.Kind); Assert.Equal(string.Empty, mr.Name); na = mr.Children.Single(); Assert.Equal(DeclarationKind.Namespace, na.Kind); Assert.Equal("NA", na.Name); nb = na.Children.Single(); Assert.Equal(DeclarationKind.Namespace, nb.Kind); Assert.Equal("NB", nb.Name); ct = nb.Children.OfType<MergedTypeDeclaration>().Single(x => x.Arity == 1); Assert.Equal(1, ct.Arity); Assert.Equal(DeclarationKind.Class, ct.Kind); Assert.Equal("C", ct.Name); c = nb.Children.OfType<MergedTypeDeclaration>().Single(x => x.Arity == 0); Assert.Equal(0, c.Arity); Assert.Equal(DeclarationKind.Class, c.Kind); Assert.Equal("C", c.Name); d = ct.Children.Single(); Assert.Equal(0, d.Arity); Assert.Equal(DeclarationKind.Class, d.Kind); Assert.Equal("D", d.Name); } private Lazy<RootSingleNamespaceDeclaration> Lazy(RootSingleNamespaceDeclaration decl) { return new Lazy<RootSingleNamespaceDeclaration>(() => decl); } [Fact] public void TestTypeNames() { var text1 = @" namespace NA.NB { partial class A<T> { partial class B { int F; } } } "; var text2 = @" namespace NA { namespace NB { partial class C<T> { partial class D { void G() {}; } } } } "; var tree1 = SyntaxFactory.ParseSyntaxTree(text1); var tree2 = SyntaxFactory.ParseSyntaxTree(text2); Assert.NotNull(tree1); Assert.NotNull(tree2); var decl1 = Lazy(DeclarationTreeBuilder.ForTree(tree1, TestOptions.DebugExe.ScriptClassName, isSubmission: false)); var decl2 = Lazy(DeclarationTreeBuilder.ForTree(tree2, TestOptions.DebugExe.ScriptClassName, isSubmission: false)); var table = DeclarationTable.Empty; table = table.AddRootDeclaration(decl1); Assert.True(table.TypeNames.OrderBy(s => s).SequenceEqual(new[] { "A", "B" })); table = table.AddRootDeclaration(decl2); Assert.True(table.TypeNames.OrderBy(s => s).SequenceEqual(new[] { "A", "B", "C", "D" })); table = table.RemoveRootDeclaration(decl2); Assert.True(table.TypeNames.OrderBy(s => s).SequenceEqual(new[] { "A", "B" })); table = table.AddRootDeclaration(decl2); Assert.True(table.TypeNames.OrderBy(s => s).SequenceEqual(new[] { "A", "B", "C", "D" })); table = table.RemoveRootDeclaration(decl1); Assert.True(table.TypeNames.OrderBy(s => s).SequenceEqual(new[] { "C", "D" })); table = table.RemoveRootDeclaration(decl2); Assert.True(table.TypeNames.IsEmpty()); } [Fact] public void Bug2038() { string code = @" public public interface testiface {}"; var comp = CSharpCompilation.Create( "Test.dll", new[] { SyntaxFactory.ParseSyntaxTree(code) }, options: TestOptions.ReleaseDll); Assert.Equal(SymbolKind.NamedType, comp.GlobalNamespace.GetMembers()[0].Kind); } [ConditionalFact(typeof(NoIOperationValidation), typeof(NoUsedAssembliesValidation))] public void OnlyOneParse() { var underlyingTree = SyntaxFactory.ParseSyntaxTree(@" using System; class C { public B X(B b) { return b; } C(){} } "); var foreignType = SyntaxFactory.ParseSyntaxTree(@" public class B { public int member(string s) { return s.Length; } B(){} } "); var countedTree = new CountedSyntaxTree(foreignType); var compilation = CreateCompilation(new SyntaxTree[] { underlyingTree, countedTree }, skipUsesIsNullable: true, options: TestOptions.ReleaseDll); var type = compilation.Assembly.GlobalNamespace.GetTypeMembers().First(); Assert.Equal(1, countedTree.AccessCount); // parse once to build the decl table // We shouldn't need to go back to syntax to get info about the member names. var memberNames = type.MemberNames; Assert.Equal(1, countedTree.AccessCount); // Getting the interfaces will cause us to do some more binding of the current type. var interfaces = type.Interfaces(); Assert.Equal(1, countedTree.AccessCount); // Now bind the members. var method = (MethodSymbol)type.GetMembers().First(); Assert.Equal(1, countedTree.AccessCount); // Once we have the method, we shouldn't need to go back to syntax again. var returnType = method.ReturnTypeWithAnnotations; Assert.Equal(1, countedTree.AccessCount); var parameterType = method.Parameters.Single(); Assert.Equal(1, countedTree.AccessCount); } /// <remarks> /// When using this type, make sure to pass an explicit CompilationOptions to CreateCompilation, as the check /// to see whether the syntax tree has top-level statements will increment the counter. /// </remarks> private class CountedSyntaxTree : CSharpSyntaxTree { private class Reference : SyntaxReference { private readonly CountedSyntaxTree _countedSyntaxTree; private readonly SyntaxReference _underlyingSyntaxReference; public Reference(CountedSyntaxTree countedSyntaxTree, SyntaxReference syntaxReference) { _countedSyntaxTree = countedSyntaxTree; _underlyingSyntaxReference = syntaxReference; } public override SyntaxTree SyntaxTree { get { return _countedSyntaxTree; } } public override TextSpan Span { get { return _underlyingSyntaxReference.Span; } } public override SyntaxNode GetSyntax(CancellationToken cancellationToken) { // Note: It's important for us to maintain identity of nodes/trees, so we find // the equivalent node in our CountedSyntaxTree. _countedSyntaxTree.AccessCount++; var nodeInUnderlying = _underlyingSyntaxReference.GetSyntax(cancellationToken); var token = _countedSyntaxTree.GetCompilationUnitRoot(cancellationToken).FindToken(nodeInUnderlying.SpanStart); for (var node = token.Parent; node != null; node = node.Parent) { if (node.Span == nodeInUnderlying.Span && node.RawKind == nodeInUnderlying.RawKind) { return (CSharpSyntaxNode)node; } } throw new Exception("Should have found the node"); } } private readonly SyntaxTree _underlyingTree; private readonly CompilationUnitSyntax _root; public int AccessCount; public CountedSyntaxTree(SyntaxTree underlying) { Debug.Assert(underlying != null); Debug.Assert(underlying.HasCompilationUnitRoot); _underlyingTree = underlying; _root = CloneNodeAsRoot(_underlyingTree.GetCompilationUnitRoot(CancellationToken.None)); } public override string FilePath { get { return _underlyingTree.FilePath; } } public override CSharpParseOptions Options { get { return (CSharpParseOptions)_underlyingTree.Options; } } public override CSharpSyntaxNode GetRoot(CancellationToken cancellationToken = default(CancellationToken)) { AccessCount++; return _root; } public override bool TryGetRoot(out CSharpSyntaxNode root) { root = _root; AccessCount++; return true; } public override bool HasCompilationUnitRoot { get { return true; } } public override SourceText GetText(CancellationToken cancellationToken) { return _underlyingTree.GetText(cancellationToken); } public override bool TryGetText(out SourceText text) { return _underlyingTree.TryGetText(out text); } public override Encoding Encoding { get { return _underlyingTree.Encoding; } } public override int Length { get { return _underlyingTree.Length; } } [Obsolete] public override ImmutableDictionary<string, ReportDiagnostic> DiagnosticOptions => throw new NotImplementedException(); public override SyntaxReference GetReference(SyntaxNode node) { return new Reference(this, _underlyingTree.GetReference(node)); } public override SyntaxTree WithChangedText(SourceText newText) { return _underlyingTree.WithChangedText(newText); } public override SyntaxTree WithRootAndOptions(SyntaxNode root, ParseOptions options) { throw new NotImplementedException(); } public override SyntaxTree WithFilePath(string path) { throw new NotImplementedException(); } } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/CodeActions/ConvertLinq/ConvertForEachToLinqQueryTests.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.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.ConvertLinq { public class ConvertForEachToLinqQueryTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CodeAnalysis.CSharp.ConvertLinq.ConvertForEachToLinqQuery.CSharpConvertForEachToLinqQueryProvider(); #region Query Expressions [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryForForWhere() { var source = @" using System.Collections.Generic; using System.Linq; class Query { public IEnumerable<int> void Main(string[] args) { List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7}; List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70}; [|foreach (var x1 in c1) { foreach (var x2 in c2) { if (object.Equals(x1, x2 / 10)) { yield return x1 + x2; } } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class Query { public IEnumerable<int> void Main(string[] args) { List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7}; List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70}; return from x1 in c1 from x2 in c2 where object.Equals(x1, x2 / 10) select x1 + x2; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class Query { public IEnumerable<int> void Main(string[] args) { List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7}; List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70}; return c1.SelectMany(x1 => c2.Where(x2 => object.Equals(x1, x2 / 10)).Select(x2 => x1 + x2)); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryWithEscapedSymbols() { var source = @" using System.Collections.Generic; using System.Linq; class Query { public IEnumerable<int> void Main(string[] args) { List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7}; List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70}; [|foreach (var @object in c1) { foreach (var x2 in c2) { yield return @object + x2; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class Query { public IEnumerable<int> void Main(string[] args) { List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7}; List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70}; return from @object in c1 from x2 in c2 select @object + x2; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class Query { public IEnumerable<int> void Main(string[] args) { List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7}; List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70}; return c1.SelectMany(@object => c2.Select(x2 => @object + x2)); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryForVarForWhere() { var source = @" using System.Linq; class C { IEnumerable<int> M() { [|foreach (var num in new int[] { 1, 2 }) { var n1 = num + 1; foreach (var a in new int[] { 5, 6 }) { foreach (var x1 in new int[] { 3, 4 }) { if (object.Equals(num, x1)) { foreach (var x2 in new int[] { 7, 8 }) { if (object.Equals(num, x2)) { var n2 = x2 - 1; yield return n2 + n1; } } } } }|] } } }"; var queryOutput = @" using System.Linq; class C { IEnumerable<int> M() { return from num in new int[] { 1, 2 } let n1 = num + 1 from a in new int[] { 5, 6 } from x1 in new int[] { 3, 4 } where object.Equals(num, x1) from x2 in new int[] { 7, 8 } where object.Equals(num, x2) let n2 = x2 - 1 select n2 + n1; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); // No linq refactoring offered due to variable declaration within the outermost foreach. await TestActionCountAsync(source, count: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryForVarForWhere_02() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M() { [|foreach (var num in new int[] { 1, 2 }) { foreach (var a in new int[] { 5, 6 }) { foreach (var x1 in new int[] { 3, 4 }) { if (object.Equals(num, x1)) { foreach (var x2 in new int[] { 7, 8 }) { if (object.Equals(num, x2)) { var n1 = num + 1; var n2 = x2 - 1; yield return n2 + n1; } } } } }|] } } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M() { return from num in new int[] { 1, 2 } from a in new int[] { 5, 6 } from x1 in new int[] { 3, 4 } where object.Equals(num, x1) from x2 in new int[] { 7, 8 } where object.Equals(num, x2) let n1 = num + 1 let n2 = x2 - 1 select n2 + n1; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M() { foreach (var (num, x2) in (new int[] { 1, 2 }).SelectMany(num => (new int[] { 5, 6 }).SelectMany(a => (new int[] { 3, 4 }).Where(x1 => object.Equals(num, x1)).SelectMany(x1 => (new int[] { 7, 8 }).Where(x2 => object.Equals(num, x2)).Select(x2 => (num, x2)))))) { var n1 = num + 1; var n2 = x2 - 1; yield return n2 + n1; } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryForVarForWhere_03() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M() { [|foreach (var num in new int[] { 1, 2 }) { foreach (var a in new int[] { 5, 6 }) { foreach (var x1 in new int[] { 3, 4 }) { var n1 = num + 1; if (object.Equals(num, x1)) { foreach (var x2 in new int[] { 7, 8 }) { if (object.Equals(num, x2)) { var n2 = x2 - 1; yield return n2 + n1; } } } } }|] } } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M() { return from num in new int[] { 1, 2 } from a in new int[] { 5, 6 } from x1 in new int[] { 3, 4 } let n1 = num + 1 where object.Equals(num, x1) from x2 in new int[] { 7, 8 } where object.Equals(num, x2) let n2 = x2 - 1 select n2 + n1; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M() { foreach (var (num, x1) in (new int[] { 1, 2 }).SelectMany(num => (new int[] { 5, 6 }).SelectMany(a => (new int[] { 3, 4 }).Select(x1 => (num, x1))))) { var n1 = num + 1; if (object.Equals(num, x1)) { foreach (var x2 in new int[] { 7, 8 }) { if (object.Equals(num, x2)) { var n2 = x2 - 1; yield return n2 + n1; } } } } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryLet() { var source = @" using System; using System.Collections.Generic; using System.Linq; class Query { void M() { List<int> c1 = new List<int>{ 1, 2, 3 }; List<int> r1 = new List<int>(); [|foreach (int x in c1) { var g = x * 10; var z = g + x*100; var a = 5 + z; r1.Add(x + z - a); }|] } }"; var queryOutput = @" using System; using System.Collections.Generic; using System.Linq; class Query { void M() { List<int> c1 = new List<int>{ 1, 2, 3 }; List<int> r1 = (from int x in c1 let g = x * 10 let z = g + x * 100 let a = 5 + z select x + z - a).ToList(); } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); // No linq invocation refactoring offered due to variable declaration(s) in topmost foreach. await TestActionCountAsync(source, count: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryEmptyDeclarations() { var source = @" using System; using System.Collections.Generic; using System.Linq; class Query { void M() { [|foreach (int x in new[] {1,2}) { int a = 3, b, c = 1; if (x > c) { b = 0; Console.Write(a + x + b); } }|] } }"; await TestMissingInRegularAndScriptAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryWhereClause() { var source = @" using System; using System.Linq; class C { IEnumerable<int> M() { var nums = new int[] { 1, 2, 3, 4 }; [|foreach (var x in nums) { if (x > 2) { yield return x; } }|] } }"; var queryOutput = @" using System; using System.Linq; class C { IEnumerable<int> M() { var nums = new int[] { 1, 2, 3, 4 }; return from x in nums where x > 2 select x; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Linq; class C { IEnumerable<int> M() { var nums = new int[] { 1, 2, 3, 4 }; return nums.Where(x => x > 2); } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryOverQueries() { var source = @" using System; using System.Linq; class C { IEnumerable<int> M() { var nums = new int[] { 1, 2, 3, 4 }; [|foreach (var y in from x in nums select x) { foreach (var z in from x in nums select x) { yield return y; } }|] } }"; var queryOutput = @" using System; using System.Linq; class C { IEnumerable<int> M() { var nums = new int[] { 1, 2, 3, 4 }; return from y in from x in nums select x from z in from x in nums select x select y; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Linq; class C { IEnumerable<int> M() { var nums = new int[] { 1, 2, 3, 4 }; return (from x in nums select x).SelectMany(y => (from x in nums select x).Select(z => y)); } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryNoVariablesUsed() { var source = @" using System; using System.Linq; class C { void M() { [|foreach (var a in new[] { 1 }) { foreach (var b in new[] { 2 }) { System.Console.Write(0); } }|] } }"; var queryOutput = @" using System; using System.Linq; class C { void M() { foreach (var _ in from a in new[] { 1 } from b in new[] { 2 } select new { }) { System.Console.Write(0); } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Linq; class C { void M() { foreach (var _ in (new[] { 1 }).SelectMany(a => (new[] { 2 }).Select(b => new { }))) { System.Console.Write(0); } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryNoBlock() { var source = @" using System; using System.Linq; class C { void M() { [|foreach (var a in new[] { 1 }) foreach (var b in new[] { 2 }) System.Console.Write(a);|] } }"; var queryOutput = @" using System; using System.Linq; class C { void M() { foreach (var a in from a in new[] { 1 } from b in new[] { 2 } select a) { System.Console.Write(a); } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Linq; class C { void M() { foreach (var a in (new[] { 1 }).SelectMany(a => (new[] { 2 }).Select(b => a))) { System.Console.Write(a); } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QuerySelectExpression() { var source = @" using System; using System.Linq; class C { void M() { [|foreach (var a in new[] { 1 }) foreach (var b in new[] { 2 }) Console.Write(a + b);|] } }"; var queryOutput = @" using System; using System.Linq; class C { void M() { foreach (var (a, b) in from a in new[] { 1 } from b in new[] { 2 } select (a, b)) { Console.Write(a + b); } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Linq; class C { void M() { foreach (var (a, b) in (new[] { 1 }).SelectMany(a => (new[] { 2 }).Select(b => (a, b)))) { Console.Write(a + b); } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QuerySelectMultipleExpressions() { var source = @" using System; using System.Linq; class C { void M() { [|foreach (var a in new[] { 1 }) foreach (var b in new[] { 2 }) { Console.Write(a + b); Console.Write(a * b); }|] } }"; var queryOutput = @" using System; using System.Linq; class C { void M() { foreach (var (a, b) in from a in new[] { 1 } from b in new[] { 2 } select (a, b)) { Console.Write(a + b); Console.Write(a * b); } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Linq; class C { void M() { foreach (var (a, b) in (new[] { 1 }).SelectMany(a => (new[] { 2 }).Select(b => (a, b)))) { Console.Write(a + b); Console.Write(a * b); } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task EmptyBody() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in from int n1 in nums from int n2 in nums select new { }) { } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in nums.SelectMany(n1 => nums.Select(n2 => new { }))) { } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task EmptyBodyNoBlock() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums); }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in from int n1 in nums from int n2 in nums select new { }) { } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in nums.SelectMany(n1 => nums.Select(n2 => new { }))) { } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task AddUsingToExistingList() { var source = @" using System.Collections.Generic; class C { void M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums); }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in from int n1 in nums from int n2 in nums select new { }) { } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in nums.SelectMany(n1 => nums.Select(n2 => new { }))) { } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task AddFirstUsing() { var source = @" class C { void M(int[] nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums); }|] } } "; var queryOutput = @"using System.Linq; class C { void M(int[] nums) { foreach (var _ in from int n1 in nums from int n2 in nums select new { }) { } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @"using System.Linq; class C { void M(int[] nums) { foreach (var _ in nums.SelectMany(n1 => nums.Select(n2 => new { }))) { } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task EmptyBodyDeclarationAsLast() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { var a = n1 + n2; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in from int n1 in nums from int n2 in nums let a = n1 + n2 select new { }) { } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var (n1, n2) in nums.SelectMany(n1 => nums.Select(n2 => (n1, n2)))) { var a = n1 + n2; } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task EmptyBodyMultipleDeclarationsAsLast() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { int a = n1 + n2, b = n1 * n2; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in from int n1 in nums from int n2 in nums let a = n1 + n2 let b = n1 * n2 select new { }) { } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var (n1, n2) in nums.SelectMany(n1 => nums.Select(n2 => (n1, n2)))) { int a = n1 + n2, b = n1 * n2; } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } #endregion #region Assignments, Declarations, Returns [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ReturnInvocationAndYieldReturn() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { yield return N(n1); } }|] } int N(int n) => n; } "; var queryOutput = @" using System; using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return from int n1 in nums from int n2 in nums select N(n1); } int N(int n) => n; } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return nums.SelectMany(n1 => nums.Select(n2 => N(n1))); } int N(int n) => n; } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task BlockBodiedProperty() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable<int> Query1 { get { [|foreach (var x in _nums) { yield return x + 1; }|] } } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; public class Test { private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable<int> Query1 { get { return from x in _nums select x + 1; } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; public class Test { private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable<int> Query1 { get { return _nums.Select(x => x + 1); } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ReturnIEnumerable() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return from int n1 in nums from int n2 in nums select n1; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return nums.SelectMany(n1 => nums.Select(n2 => n1)); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ReturnIEnumerableWithYieldReturnAndLocalFunction() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<IEnumerable<int>> M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { yield return f(n1); } }|] yield break; IEnumerable<int> f(int a) { yield return a; } } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<IEnumerable<int>> M(IEnumerable<int> nums) { return from int n1 in nums from int n2 in nums select f(n1); IEnumerable<int> f(int a) { yield return a; } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<IEnumerable<int>> M(IEnumerable<int> nums) { return nums.SelectMany(n1 => nums.Select(n2 => f(n1))); IEnumerable<int> f(int a) { yield return a; } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ReturnIEnumerablePartialMethod() { var source = @" using System.Collections.Generic; using System.Linq; partial class C { partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { partial IEnumerable<int> M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } }|] yield break; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; partial class C { partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { partial IEnumerable<int> M(IEnumerable<int> nums) { return from int n1 in nums from int n2 in nums select n1; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; partial class C { partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { partial IEnumerable<int> M(IEnumerable<int> nums) { return nums.SelectMany(n1 => nums.Select(n2 => n1)); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ReturnIEnumerableExtendedPartialMethod() { var source = @" using System.Collections.Generic; using System.Linq; partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } }|] yield break; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums) { return from int n1 in nums from int n2 in nums select n1; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums) { return nums.SelectMany(n1 => nums.Select(n2 => n1)); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] [WorkItem(31784, "https://github.com/dotnet/roslyn/issues/31784")] public async Task QueryWhichRequiresSelectManyWithIdentityLambda() { var source = @" using System.Collections.Generic; class C { IEnumerable<int> M() { [|foreach (var x in new[] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 } }) { foreach (var y in x) { yield return y; } }|] } } "; var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M() { return (new[] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 } }).SelectMany(x => x); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } #endregion #region In foreach [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryInForEachWithSameVariableNameAndDifferentType() { var source = @" using System; using System.Collections.Generic; using System.Linq; class A { public static implicit operator int(A x) { throw null; } public static implicit operator A(int x) { throw null; } } class B : A { } class C { void M(IEnumerable<int> nums) { [|foreach (B a in nums) { foreach (A c in nums) { Console.Write(a.ToString()); } }|] } } "; var queryOutput = @" using System; using System.Collections.Generic; using System.Linq; class A { public static implicit operator int(A x) { throw null; } public static implicit operator A(int x) { throw null; } } class B : A { } class C { void M(IEnumerable<int> nums) { foreach (var a in from B a in nums from A c in nums select a) { Console.Write(a.ToString()); } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Collections.Generic; using System.Linq; class A { public static implicit operator int(A x) { throw null; } public static implicit operator A(int x) { throw null; } } class B : A { } class C { void M(IEnumerable<int> nums) { foreach (var a in nums.SelectMany(a => nums.Select(c => a))) { Console.Write(a.ToString()); } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryInForEachWithSameVariableNameAndSameType() { var source = @" using System; using System.Collections.Generic; using System.Linq; class A { public static implicit operator int(A x) { throw null; } public static implicit operator A(int x) { throw null; } } class C { void M(IEnumerable<int> nums) { [|foreach (A a in nums) { foreach (A c in nums) { Console.Write(a.ToString()); } }|] } } "; var queryOutput = @" using System; using System.Collections.Generic; using System.Linq; class A { public static implicit operator int(A x) { throw null; } public static implicit operator A(int x) { throw null; } } class C { void M(IEnumerable<int> nums) { foreach (var a in from A a in nums from A c in nums select a) { Console.Write(a.ToString()); } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Collections.Generic; using System.Linq; class A { public static implicit operator int(A x) { throw null; } public static implicit operator A(int x) { throw null; } } class C { void M(IEnumerable<int> nums) { foreach (var a in nums.SelectMany(a => nums.Select(c => a))) { Console.Write(a.ToString()); } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryInForEachWithConvertedType() { var source = @" using System; using System.Collections.Generic; static class Extensions { public static IEnumerable<C> Select(this int[] x, Func<int, C> predicate) => throw null; } class C { public static implicit operator int(C x) { throw null; } public static implicit operator C(int x) { throw null; } IEnumerable<C> Test() { [|foreach (var x in new[] { 1, 2, 3 }) { yield return x; }|] } } "; var queryOutput = @" using System; using System.Collections.Generic; using System.Linq; static class Extensions { public static IEnumerable<C> Select(this int[] x, Func<int, C> predicate) => throw null; } class C { public static implicit operator int(C x) { throw null; } public static implicit operator C(int x) { throw null; } IEnumerable<C> Test() { return from x in new[] { 1, 2, 3 } select x; } } "; await TestAsync(source, queryOutput, parseOptions: null); var linqInvocationOutput = @" using System; using System.Collections.Generic; using System.Linq; static class Extensions { public static IEnumerable<C> Select(this int[] x, Func<int, C> predicate) => throw null; } class C { public static implicit operator int(C x) { throw null; } public static implicit operator C(int x) { throw null; } IEnumerable<C> Test() { return new[] { 1, 2, 3 }; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task IQueryableConvertedToIEnumerableInReturn() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { [|foreach (int n1 in nums.AsQueryable()) { yield return n1; }|] yield break; } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return from int n1 in nums.AsQueryable() select n1; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return nums.AsQueryable(); } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ReturnIQueryableConvertedToIEnumerableInAssignment() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { [|foreach (int n1 in nums.AsQueryable()) { yield return n1; }|] } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return from int n1 in nums.AsQueryable() select n1; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return nums.AsQueryable(); } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } #endregion #region In ToList [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListLastDeclarationMerge() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list0 = new List<int>(), list = new List<int>(); [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list0 = new List<int>(); return (from int n1 in nums from int n2 in nums select n1).ToList(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list0 = new List<int>(); return (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListParameterizedConstructor() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>(nums); [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>(nums); list.AddRange(from int n1 in nums from int n2 in nums select n1); return list; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>(nums); list.AddRange(nums.SelectMany(n1 => nums.Select(n2 => n1))); return list; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListWithListInitializer() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>() { 1, 2, 3 }; [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>() { 1, 2, 3 }; list.AddRange(from int n1 in nums from int n2 in nums select n1); return list; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>() { 1, 2, 3 }; list.AddRange(nums.SelectMany(n1 => nums.Select(n2 => n1))); return list; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListWithEmptyArgumentList() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int> { }; [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { return (from int n1 in nums from int n2 in nums select n1).ToList(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { return (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListNotLastDeclaration() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>(), list1 = new List<int>(); [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>(), list1 = new List<int>(); list.AddRange(from int n1 in nums from int n2 in nums select n1); return list; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>(), list1 = new List<int>(); list.AddRange(nums.SelectMany(n1 => nums.Select(n2 => n1))); return list; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListAssignToParameter() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums, List<int> list) { list = new List<int>(); [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums, List<int> list) { list = (from int n1 in nums from int n2 in nums select n1).ToList(); return list; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums, List<int> list) { list = (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList(); return list; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListToArrayElement() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, List<int>[] lists) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { lists[0].Add(n1); } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, List<int>[] lists) { lists[0].AddRange(from int n1 in nums from int n2 in nums select n1); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, List<int>[] lists) { lists[0].AddRange(nums.SelectMany(n1 => nums.Select(n2 => n1))); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListToNewArrayElement() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, List<int>[] lists) { lists[0] = new List<int>(); [|foreach (int n1 in nums) { foreach (int n2 in nums) { lists[0].Add(n1); } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, List<int>[] lists) { lists[0] = (from int n1 in nums from int n2 in nums select n1).ToList(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, List<int>[] lists) { lists[0] = (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListHashSetNoConversion() { var source = @" using System.Collections.Generic; class C { void M(IEnumerable<int> nums) { var hashSet = new HashSet<int>(); [|foreach (int n1 in nums) { hashSet.Add(n1); }|] } } "; await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListMergeWithReturn() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { var list = new List<int>(); [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { return (from int n1 in nums from int n2 in nums select n1).ToList(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { return (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListSeparateDeclarationAndAssignmentMergeWithReturn() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list; list = new List<int>(); [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list; return (from int n1 in nums from int n2 in nums select n1).ToList(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list; return (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListSeparateDeclarationAndAssignment() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { List<int> list; list = new List<int>(); [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list.Count; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { List<int> list; list = (from int n1 in nums from int n2 in nums select n1).ToList(); return list.Count; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { List<int> list; list = (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList(); return list.Count; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListTypeReplacement01() { var source = @" using System; using System.Linq; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C c3 = new C { 100, 200, 300 }; C r1 = new C(); [|foreach (int x in c1) { foreach (int y in c2) { foreach (int z in c3) { var g = x + y + z; if (x + y / 10 + z / 100 < 6) { r1.Add(g); } } } }|] Console.WriteLine(r1); } } "; var queryOutput = @" using System; using System.Linq; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C c3 = new C { 100, 200, 300 }; C r1 = (from int x in c1 from int y in c2 from int z in c3 let g = x + y + z where x + y / 10 + z / 100 < 6 select g).ToList(); Console.WriteLine(r1); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Linq; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C c3 = new C { 100, 200, 300 }; C r1 = new C(); foreach (var (x, y, z) in c1.SelectMany(x => c2.SelectMany(y => c3.Select(z => (x, y, z))))) { var g = x + y + z; if (x + y / 10 + z / 100 < 6) { r1.Add(g); } } Console.WriteLine(r1); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListTypeReplacement02() { var source = @" using System.Linq; using System; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C r1 = new C(); [|foreach (int x in c1) { foreach (var y in c2) { if (Equals(x, y / 10)) { var z = x + y; r1.Add(z); } } }|] Console.WriteLine(r1); } } "; var queryOutput = @" using System.Linq; using System; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C r1 = (from int x in c1 from y in c2 where Equals(x, y / 10) let z = x + y select z).ToList(); Console.WriteLine(r1); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Linq; using System; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C r1 = new C(); foreach (var (x, y) in c1.SelectMany(x => c2.Where(y => Equals(x, y / 10)).Select(y => (x, y)))) { var z = x + y; r1.Add(z); } Console.WriteLine(r1); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListPropertyAssignment() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); c.A = new List<int>(); [|foreach (var x in nums) { c.A.Add(x + 1); }|] } class C { public List<int> A { get; set; } } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); c.A = (from x in nums select x + 1).ToList(); } class C { public List<int> A { get; set; } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); c.A = (nums.Select(x => x + 1)).ToList(); } class C { public List<int> A { get; set; } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListPropertyAssignmentNoDeclaration() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { void M() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); [|foreach (var x in nums) { c.A.Add(x + 1); }|] } class C { public List<int> A { get; set; } } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; public class Test { void M() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); c.A.AddRange(from x in nums select x + 1); } class C { public List<int> A { get; set; } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; public class Test { void M() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); c.A.AddRange(nums.Select(x => x + 1)); } class C { public List<int> A { get; set; } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListNoInitialization() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { public List<int> A { get; set; } void M() { [|foreach (var x in new int[] { 1, 2, 3, 4 }) { A.Add(x + 1); }|] } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; public class Test { public List<int> A { get; set; } void M() { A.AddRange(from x in new int[] { 1, 2, 3, 4 } select x + 1); } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; public class Test { public List<int> A { get; set; } void M() { A.AddRange((new int[] { 1, 2, 3, 4 }).Select(x => x + 1)); } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListOverride() { var source = @" using System.Collections.Generic; using System.Linq; public static class C { public static void Add<T>(this List<T> list, T value, T anotherValue) { } } public class Test { void M() { var list = new List<int>(); [|foreach (var x in new int[] { 1, 2, 3, 4 }) { list.Add(x + 1, x); }|] } }"; await TestMissingAsync(source); } #endregion #region In Count [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInMultipleDeclarationLast() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int i = 0, cnt = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int i = 0, cnt = (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int i = 0, cnt = (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInMultipleDeclarationNotLast() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int cnt = 0, i = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int cnt = 0, i = 0; cnt += (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int cnt = 0, i = 0; cnt += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInParameter() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { c++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c += (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInParameterAssignedToZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { c++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c = (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c = (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInParameterAssignedToNonZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c = 5; [|foreach (int n1 in nums) { foreach (int n2 in nums) { c++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c = 5; c += (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c = 5; c += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInDeclarationMergeToReturn() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { var cnt = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] return cnt; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { return (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { return (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInDeclarationConversion() { var source = @" using System.Collections.Generic; using System.Linq; class C { double M(IEnumerable<int> nums) { double c = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { c++; } }|] return c; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { double M(IEnumerable<int> nums) { return (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { double M(IEnumerable<int> nums) { return (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInMultipleDeclarationMergeToReturnLast() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int c = 0, cnt = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] return cnt; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int c = 0; return (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int c = 0; return (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInMultipleDeclarationLastButNotZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int c = 0, cnt = 5; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] return cnt; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int c = 0, cnt = 5; cnt += (from int n1 in nums from int n2 in nums select n1).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int c = 0, cnt = 5; cnt += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInMultipleDeclarationMergeToReturnNotLast() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt = 0, c = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] return cnt; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt = 0, c = 0; cnt += (from int n1 in nums from int n2 in nums select n1).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt = 0, c = 0; cnt += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInMultipleDeclarationNonZeroToReturnNotLast() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt = 5, c = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] return cnt; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt = 5, c = 0; cnt += (from int n1 in nums from int n2 in nums select n1).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt = 5, c = 0; cnt += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInAssignmentToZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt; cnt = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] return cnt; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt; return (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt; return (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInAssignmentToNonZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt; cnt = 5; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] return cnt; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt; cnt = 5; cnt += (from int n1 in nums from int n2 in nums select n1).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt; cnt = 5; cnt += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInParameterAssignedToZeroAndReturned() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums, int c) { c = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { c++; } }|] return c; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums, int c) { c = (from int n1 in nums from int n2 in nums select n1).Count(); return c; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums, int c) { c = (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); return c; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountDeclareWithNonZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var count = 5; [|foreach (int n1 in nums) { foreach (int n2 in nums) { count++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var count = 5; count += (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var count = 5; count += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountAssignWithZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int count = 1; count = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { count++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int count = 1; count = (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int count = 1; count = (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountAssignWithNonZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var count = 0; count = 4; [|foreach (int n1 in nums) { foreach (int n2 in nums) { count++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var count = 0; count = 4; count += (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var count = 0; count = 4; count += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountAssignPropertyAssignedToZero() { var source = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { a.B++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B = (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B = (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountAssignPropertyAssignedToNonZero() { var source = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B = 5; [|foreach (int n1 in nums) { foreach (int n2 in nums) { a.B++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B = 5; a.B += (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B = 5; a.B += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountAssignPropertyNotKnownAssigned() { var source = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { a.B++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B += (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountIQueryableInInvocation() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int c = 0; [|foreach (int n1 in nums.AsQueryable()) { c++; }|] } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int c = (from int n1 in nums.AsQueryable() select n1).Count(); } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int c = (nums.AsQueryable()).Count(); } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } #endregion #region Comments [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CommentsYieldReturn() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { [|// 1 foreach /* 2 */( /* 3 */ var /* 4 */ x /* 5 */ in /* 6 */ nums /* 7 */)// 8 { // 9 /* 10 */ foreach /* 11 */ (/* 12 */ int /* 13 */ y /* 14 */ in /* 15 */ nums /* 16 */)/* 17 */ // 18 {// 19 /*20 */ if /* 21 */(/* 22 */ x > 2 /* 23 */) // 24 { // 25 /* 26 */ yield /* 27 */ return /* 28 */ x * y /* 29 */; // 30 /* 31 */ }// 32 /* 33 */ } // 34 /* 35 */ }|] /* 36 */ /* 37 */ yield /* 38 */ break/* 39*/; // 40 } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return // 25 // 1 from/* 3 *//* 2 *//* 4 */x /* 5 */ in/* 6 */nums/* 7 */// 8 // 9 /* 10 */ from/* 12 *//* 11 */int /* 13 */ y /* 14 */ in/* 15 */nums/* 16 *//* 17 */// 18 // 19 /*20 */ where/* 21 *//* 22 */x > 2/* 23 */// 24 /* 26 *//* 27 *//* 28 */ select x * y/* 29 *//* 31 */// 32 /* 33 */// 34 /* 35 *//* 36 */// 30 /* 37 *//* 38 *//* 39*/// 40 ; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return nums /* 7 */.SelectMany( // 1 /* 2 */// 25 /* 4 */x /* 5 */ => nums /* 16 */.Where( /*20 *//* 21 */// 19 y => /* 22 */x > 2/* 23 */// 24 ).Select( // 9 /* 10 *//* 11 *//* 13 */y /* 14 */ => /* 26 *//* 27 *//* 28 */x * y/* 29 *//* 31 */// 32 /* 33 */// 34 /* 35 *//* 36 */// 30 /* 37 *//* 38 *//* 39*/// 40 /* 12 *//* 15 *//* 17 */// 18 )/* 3 *//* 6 */// 8 ); } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CommentsToList() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { /* 1 */ var /* 2 */ list /* 3 */ = /* 4 */ new List<int>(); // 5 /* 6 */ [|foreach /* 7 */ (/* 8 */ var /* 9 */ x /* 10 */ in /* 11 */ nums /* 12 */) // 13 /* 14 */{ // 15 /* 16 */var /* 17 */ y /* 18 */ = /* 19 */ x + 1 /* 20 */; //21 /* 22 */ list.Add(/* 23 */y /* 24 */) /* 25 */;//26 /*27*/} //28|] /*29*/return /*30*/ list /*31*/; //32 } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { /*29*/ return /*30*/ /* 1 *//* 2 *//* 3 *//* 4 */// 5 /*31*/ ( /* 6 */from/* 8 *//* 7 *//* 9 */x /* 10 */ in/* 11 */nums/* 12 */// 13 /* 14 */// 15 /* 16 *//* 17 */ let y /* 18 */ = /* 19 */ x + 1/* 20 *///21 select y/* 24 *//*27*///28 ).ToList()/* 22 *//* 23 *//* 25 *///26 ; //32 } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); // No linq refactoring offered due to variable declaration in outermost foreach. await TestActionCountAsync(source, count: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CommentsToList_02() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { /* 1 */ var /* 2 */ list /* 3 */ = /* 4 */ new List<int>(); // 5 /* 6 */ [|foreach /* 7 */ (/* 8 */ var /* 9 */ x /* 10 */ in /* 11 */ nums /* 12 */) // 13 /* 14 */{ // 15 /* 16 */ list.Add(/* 17 */ x + 1 /* 18 */) /* 19 */;//20 /*21*/} //22|] /*23*/return /*24*/ list /*25*/; //26 } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { /*23*/ return /*24*/ /* 1 *//* 2 *//* 3 *//* 4 */// 5 /*25*/ ( /* 14 */// 15 /* 6 */from/* 8 *//* 7 *//* 9 */x /* 10 */ in/* 11 */nums/* 12 */// 13 select x + 1/* 18 *//*21*///22 ).ToList()/* 16 *//* 17 *//* 19 *///20 ; //26 } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { /*23*/ return /*24*/ /* 1 *//* 2 *//* 3 *//* 4 */// 5 /*25*/ (nums /* 12 */.Select( /* 6 *//* 7 *//* 14 */// 15 /* 9 */x /* 10 */ => x + 1/* 18 *//*21*///22 /* 8 *//* 11 */// 13 )).ToList()/* 16 *//* 17 *//* 19 *///20 ; //26 } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CommentsCount() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { /* 1 */ var /* 2 */ c /* 3 */ = /* 4 */ 0; // 5 /* 6 */ [| foreach /* 7 */ (/* 8 */ var /* 9 */ x /* 10 */ in /* 11 */ nums /* 12 */) // 13 /* 14 */{ // 15 /* 16 */ c++ /* 17 */;//18 /*19*/}|] //20 /*21*/return /*22*/ c /*23*/; //24 } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { /*21*/ return /*22*/ /* 1 *//* 2 *//* 3 *//* 4 */// 5 /*23*/ ( /* 14 */// 15 /* 6 */from/* 8 *//* 7 *//* 9 */x /* 10 */ in/* 11 */nums/* 12 */// 13 select x/* 10 *//*19*///20 ).Count()/* 16 *//* 17 *///18 ; //24 } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { /*21*/ return /*22*/ /* 1 *//* 2 *//* 3 *//* 4 */// 5 /*23*/ (nums /* 12 *//* 6 *//* 7 *//* 14 */// 15 /* 9 *//* 10 *//* 10 *//*19*///20 /* 8 *//* 11 */// 13 ).Count()/* 16 *//* 17 *///18 ; //24 } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CommentsDefault() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { [|/* 1 */ foreach /* 2 */(int /* 3 */ n1 /* 4 */in /* 5 */ nums /* 6 */)// 7 /* 8*/{// 9 /* 10 */int /* 11 */ a /* 12 */ = /* 13 */ n1 + n1 /* 14*/, /* 15 */ b /*16*/ = /*17*/ n1 * n1/*18*/;//19 /*20*/Console.WriteLine(a + b);//21 /*22*/}/*23*/|] } }"; var queryOutput = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var (a /* 12 */ , b /*16*/ ) in /* 1 */from/* 2 */int /* 3 */ n1 /* 4 */in/* 5 */nums/* 6 */// 7 /* 8*/// 9 /* 10 *//* 11 */ let a /* 12 */ = /* 13 */ n1 + n1/* 14*//* 15 */ let b /*16*/ = /*17*/ n1 * n1/*18*///19 select (a /* 12 */ , b /*16*/ )/*22*//*23*/) { /*20*/ Console.WriteLine(a + b);//21 } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); // No linq refactoring offered due to variable declaration(s) in outermost foreach. await TestActionCountAsync(source, count: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CommentsDefault_02() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { [|/* 1 */ foreach /* 2 */(int /* 3 */ n1 /* 4 */in /* 5 */ nums /* 6 */)// 7 /* 8*/{// 9 /* 10 */ if /* 11 */ (/* 12 */ n1 /* 13 */ > /* 14 */ 0/* 15 */ ) // 16 /* 17 */{ // 18 /*19*/Console.WriteLine(n1);//20 /* 21 */} // 22 /*23*/}/*24*/|] } }"; var queryOutput = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var n1 /* 4 */in /* 17 */// 18 /* 1 */from/* 2 */int /* 3 */ n1 /* 4 */in/* 5 */nums/* 6 */// 7 /* 8*/// 9 /* 10 */ where/* 11 *//* 12 */n1 /* 13 */ > /* 14 */ 0/* 15 */// 16 select n1/* 4 *//* 21 */// 22 /*23*//*24*/ ) { /*19*/ Console.WriteLine(n1);//20 } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var n1 /* 4 */in nums /* 6 */.Where( /* 10 *//* 11 *//* 8*/// 9 n1 => /* 12 */n1 /* 13 */ > /* 14 */ 0/* 15 */// 16 ) /* 1 *//* 2 *//* 17 */// 18 /* 3 *//* 4 *//* 4 *//* 21 */// 22 /*23*//*24*//* 5 */// 7 ) { /*19*/ Console.WriteLine(n1);//20 } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } #endregion #region Preprocessor directives [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task NoConversionPreprocessorDirectives() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { [|foreach(var x in nums) { #if (true) yield return x + 1; #endif }|] } }"; // Cannot convert expressions with preprocessor directives await TestMissingAsync(source); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.ConvertLinq { public class ConvertForEachToLinqQueryTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CodeAnalysis.CSharp.ConvertLinq.ConvertForEachToLinqQuery.CSharpConvertForEachToLinqQueryProvider(); #region Query Expressions [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryForForWhere() { var source = @" using System.Collections.Generic; using System.Linq; class Query { public IEnumerable<int> void Main(string[] args) { List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7}; List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70}; [|foreach (var x1 in c1) { foreach (var x2 in c2) { if (object.Equals(x1, x2 / 10)) { yield return x1 + x2; } } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class Query { public IEnumerable<int> void Main(string[] args) { List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7}; List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70}; return from x1 in c1 from x2 in c2 where object.Equals(x1, x2 / 10) select x1 + x2; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class Query { public IEnumerable<int> void Main(string[] args) { List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7}; List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70}; return c1.SelectMany(x1 => c2.Where(x2 => object.Equals(x1, x2 / 10)).Select(x2 => x1 + x2)); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryWithEscapedSymbols() { var source = @" using System.Collections.Generic; using System.Linq; class Query { public IEnumerable<int> void Main(string[] args) { List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7}; List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70}; [|foreach (var @object in c1) { foreach (var x2 in c2) { yield return @object + x2; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class Query { public IEnumerable<int> void Main(string[] args) { List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7}; List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70}; return from @object in c1 from x2 in c2 select @object + x2; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class Query { public IEnumerable<int> void Main(string[] args) { List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7}; List<int> c2 = new List<int>{10, 30, 40, 50, 60, 70}; return c1.SelectMany(@object => c2.Select(x2 => @object + x2)); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryForVarForWhere() { var source = @" using System.Linq; class C { IEnumerable<int> M() { [|foreach (var num in new int[] { 1, 2 }) { var n1 = num + 1; foreach (var a in new int[] { 5, 6 }) { foreach (var x1 in new int[] { 3, 4 }) { if (object.Equals(num, x1)) { foreach (var x2 in new int[] { 7, 8 }) { if (object.Equals(num, x2)) { var n2 = x2 - 1; yield return n2 + n1; } } } } }|] } } }"; var queryOutput = @" using System.Linq; class C { IEnumerable<int> M() { return from num in new int[] { 1, 2 } let n1 = num + 1 from a in new int[] { 5, 6 } from x1 in new int[] { 3, 4 } where object.Equals(num, x1) from x2 in new int[] { 7, 8 } where object.Equals(num, x2) let n2 = x2 - 1 select n2 + n1; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); // No linq refactoring offered due to variable declaration within the outermost foreach. await TestActionCountAsync(source, count: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryForVarForWhere_02() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M() { [|foreach (var num in new int[] { 1, 2 }) { foreach (var a in new int[] { 5, 6 }) { foreach (var x1 in new int[] { 3, 4 }) { if (object.Equals(num, x1)) { foreach (var x2 in new int[] { 7, 8 }) { if (object.Equals(num, x2)) { var n1 = num + 1; var n2 = x2 - 1; yield return n2 + n1; } } } } }|] } } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M() { return from num in new int[] { 1, 2 } from a in new int[] { 5, 6 } from x1 in new int[] { 3, 4 } where object.Equals(num, x1) from x2 in new int[] { 7, 8 } where object.Equals(num, x2) let n1 = num + 1 let n2 = x2 - 1 select n2 + n1; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M() { foreach (var (num, x2) in (new int[] { 1, 2 }).SelectMany(num => (new int[] { 5, 6 }).SelectMany(a => (new int[] { 3, 4 }).Where(x1 => object.Equals(num, x1)).SelectMany(x1 => (new int[] { 7, 8 }).Where(x2 => object.Equals(num, x2)).Select(x2 => (num, x2)))))) { var n1 = num + 1; var n2 = x2 - 1; yield return n2 + n1; } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryForVarForWhere_03() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M() { [|foreach (var num in new int[] { 1, 2 }) { foreach (var a in new int[] { 5, 6 }) { foreach (var x1 in new int[] { 3, 4 }) { var n1 = num + 1; if (object.Equals(num, x1)) { foreach (var x2 in new int[] { 7, 8 }) { if (object.Equals(num, x2)) { var n2 = x2 - 1; yield return n2 + n1; } } } } }|] } } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M() { return from num in new int[] { 1, 2 } from a in new int[] { 5, 6 } from x1 in new int[] { 3, 4 } let n1 = num + 1 where object.Equals(num, x1) from x2 in new int[] { 7, 8 } where object.Equals(num, x2) let n2 = x2 - 1 select n2 + n1; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M() { foreach (var (num, x1) in (new int[] { 1, 2 }).SelectMany(num => (new int[] { 5, 6 }).SelectMany(a => (new int[] { 3, 4 }).Select(x1 => (num, x1))))) { var n1 = num + 1; if (object.Equals(num, x1)) { foreach (var x2 in new int[] { 7, 8 }) { if (object.Equals(num, x2)) { var n2 = x2 - 1; yield return n2 + n1; } } } } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryLet() { var source = @" using System; using System.Collections.Generic; using System.Linq; class Query { void M() { List<int> c1 = new List<int>{ 1, 2, 3 }; List<int> r1 = new List<int>(); [|foreach (int x in c1) { var g = x * 10; var z = g + x*100; var a = 5 + z; r1.Add(x + z - a); }|] } }"; var queryOutput = @" using System; using System.Collections.Generic; using System.Linq; class Query { void M() { List<int> c1 = new List<int>{ 1, 2, 3 }; List<int> r1 = (from int x in c1 let g = x * 10 let z = g + x * 100 let a = 5 + z select x + z - a).ToList(); } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); // No linq invocation refactoring offered due to variable declaration(s) in topmost foreach. await TestActionCountAsync(source, count: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryEmptyDeclarations() { var source = @" using System; using System.Collections.Generic; using System.Linq; class Query { void M() { [|foreach (int x in new[] {1,2}) { int a = 3, b, c = 1; if (x > c) { b = 0; Console.Write(a + x + b); } }|] } }"; await TestMissingInRegularAndScriptAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryWhereClause() { var source = @" using System; using System.Linq; class C { IEnumerable<int> M() { var nums = new int[] { 1, 2, 3, 4 }; [|foreach (var x in nums) { if (x > 2) { yield return x; } }|] } }"; var queryOutput = @" using System; using System.Linq; class C { IEnumerable<int> M() { var nums = new int[] { 1, 2, 3, 4 }; return from x in nums where x > 2 select x; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Linq; class C { IEnumerable<int> M() { var nums = new int[] { 1, 2, 3, 4 }; return nums.Where(x => x > 2); } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryOverQueries() { var source = @" using System; using System.Linq; class C { IEnumerable<int> M() { var nums = new int[] { 1, 2, 3, 4 }; [|foreach (var y in from x in nums select x) { foreach (var z in from x in nums select x) { yield return y; } }|] } }"; var queryOutput = @" using System; using System.Linq; class C { IEnumerable<int> M() { var nums = new int[] { 1, 2, 3, 4 }; return from y in from x in nums select x from z in from x in nums select x select y; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Linq; class C { IEnumerable<int> M() { var nums = new int[] { 1, 2, 3, 4 }; return (from x in nums select x).SelectMany(y => (from x in nums select x).Select(z => y)); } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryNoVariablesUsed() { var source = @" using System; using System.Linq; class C { void M() { [|foreach (var a in new[] { 1 }) { foreach (var b in new[] { 2 }) { System.Console.Write(0); } }|] } }"; var queryOutput = @" using System; using System.Linq; class C { void M() { foreach (var _ in from a in new[] { 1 } from b in new[] { 2 } select new { }) { System.Console.Write(0); } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Linq; class C { void M() { foreach (var _ in (new[] { 1 }).SelectMany(a => (new[] { 2 }).Select(b => new { }))) { System.Console.Write(0); } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryNoBlock() { var source = @" using System; using System.Linq; class C { void M() { [|foreach (var a in new[] { 1 }) foreach (var b in new[] { 2 }) System.Console.Write(a);|] } }"; var queryOutput = @" using System; using System.Linq; class C { void M() { foreach (var a in from a in new[] { 1 } from b in new[] { 2 } select a) { System.Console.Write(a); } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Linq; class C { void M() { foreach (var a in (new[] { 1 }).SelectMany(a => (new[] { 2 }).Select(b => a))) { System.Console.Write(a); } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QuerySelectExpression() { var source = @" using System; using System.Linq; class C { void M() { [|foreach (var a in new[] { 1 }) foreach (var b in new[] { 2 }) Console.Write(a + b);|] } }"; var queryOutput = @" using System; using System.Linq; class C { void M() { foreach (var (a, b) in from a in new[] { 1 } from b in new[] { 2 } select (a, b)) { Console.Write(a + b); } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Linq; class C { void M() { foreach (var (a, b) in (new[] { 1 }).SelectMany(a => (new[] { 2 }).Select(b => (a, b)))) { Console.Write(a + b); } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QuerySelectMultipleExpressions() { var source = @" using System; using System.Linq; class C { void M() { [|foreach (var a in new[] { 1 }) foreach (var b in new[] { 2 }) { Console.Write(a + b); Console.Write(a * b); }|] } }"; var queryOutput = @" using System; using System.Linq; class C { void M() { foreach (var (a, b) in from a in new[] { 1 } from b in new[] { 2 } select (a, b)) { Console.Write(a + b); Console.Write(a * b); } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Linq; class C { void M() { foreach (var (a, b) in (new[] { 1 }).SelectMany(a => (new[] { 2 }).Select(b => (a, b)))) { Console.Write(a + b); Console.Write(a * b); } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task EmptyBody() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in from int n1 in nums from int n2 in nums select new { }) { } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in nums.SelectMany(n1 => nums.Select(n2 => new { }))) { } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task EmptyBodyNoBlock() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums); }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in from int n1 in nums from int n2 in nums select new { }) { } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in nums.SelectMany(n1 => nums.Select(n2 => new { }))) { } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task AddUsingToExistingList() { var source = @" using System.Collections.Generic; class C { void M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums); }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in from int n1 in nums from int n2 in nums select new { }) { } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in nums.SelectMany(n1 => nums.Select(n2 => new { }))) { } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task AddFirstUsing() { var source = @" class C { void M(int[] nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums); }|] } } "; var queryOutput = @"using System.Linq; class C { void M(int[] nums) { foreach (var _ in from int n1 in nums from int n2 in nums select new { }) { } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @"using System.Linq; class C { void M(int[] nums) { foreach (var _ in nums.SelectMany(n1 => nums.Select(n2 => new { }))) { } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task EmptyBodyDeclarationAsLast() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { var a = n1 + n2; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in from int n1 in nums from int n2 in nums let a = n1 + n2 select new { }) { } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var (n1, n2) in nums.SelectMany(n1 => nums.Select(n2 => (n1, n2)))) { var a = n1 + n2; } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task EmptyBodyMultipleDeclarationsAsLast() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { int a = n1 + n2, b = n1 * n2; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var _ in from int n1 in nums from int n2 in nums let a = n1 + n2 let b = n1 * n2 select new { }) { } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var (n1, n2) in nums.SelectMany(n1 => nums.Select(n2 => (n1, n2)))) { int a = n1 + n2, b = n1 * n2; } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } #endregion #region Assignments, Declarations, Returns [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ReturnInvocationAndYieldReturn() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { yield return N(n1); } }|] } int N(int n) => n; } "; var queryOutput = @" using System; using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return from int n1 in nums from int n2 in nums select N(n1); } int N(int n) => n; } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return nums.SelectMany(n1 => nums.Select(n2 => N(n1))); } int N(int n) => n; } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task BlockBodiedProperty() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable<int> Query1 { get { [|foreach (var x in _nums) { yield return x + 1; }|] } } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; public class Test { private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable<int> Query1 { get { return from x in _nums select x + 1; } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; public class Test { private readonly int[] _nums = new int[] { 1, 2, 3, 4 }; public IEnumerable<int> Query1 { get { return _nums.Select(x => x + 1); } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ReturnIEnumerable() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return from int n1 in nums from int n2 in nums select n1; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return nums.SelectMany(n1 => nums.Select(n2 => n1)); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ReturnIEnumerableWithYieldReturnAndLocalFunction() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<IEnumerable<int>> M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { yield return f(n1); } }|] yield break; IEnumerable<int> f(int a) { yield return a; } } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<IEnumerable<int>> M(IEnumerable<int> nums) { return from int n1 in nums from int n2 in nums select f(n1); IEnumerable<int> f(int a) { yield return a; } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<IEnumerable<int>> M(IEnumerable<int> nums) { return nums.SelectMany(n1 => nums.Select(n2 => f(n1))); IEnumerable<int> f(int a) { yield return a; } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ReturnIEnumerablePartialMethod() { var source = @" using System.Collections.Generic; using System.Linq; partial class C { partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { partial IEnumerable<int> M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } }|] yield break; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; partial class C { partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { partial IEnumerable<int> M(IEnumerable<int> nums) { return from int n1 in nums from int n2 in nums select n1; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; partial class C { partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { partial IEnumerable<int> M(IEnumerable<int> nums) { return nums.SelectMany(n1 => nums.Select(n2 => n1)); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ReturnIEnumerableExtendedPartialMethod() { var source = @" using System.Collections.Generic; using System.Linq; partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { yield return n1; } }|] yield break; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums) { return from int n1 in nums from int n2 in nums select n1; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums); } partial class C { public partial IEnumerable<int> M(IEnumerable<int> nums) { return nums.SelectMany(n1 => nums.Select(n2 => n1)); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] [WorkItem(31784, "https://github.com/dotnet/roslyn/issues/31784")] public async Task QueryWhichRequiresSelectManyWithIdentityLambda() { var source = @" using System.Collections.Generic; class C { IEnumerable<int> M() { [|foreach (var x in new[] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 } }) { foreach (var y in x) { yield return y; } }|] } } "; var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M() { return (new[] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 } }).SelectMany(x => x); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } #endregion #region In foreach [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryInForEachWithSameVariableNameAndDifferentType() { var source = @" using System; using System.Collections.Generic; using System.Linq; class A { public static implicit operator int(A x) { throw null; } public static implicit operator A(int x) { throw null; } } class B : A { } class C { void M(IEnumerable<int> nums) { [|foreach (B a in nums) { foreach (A c in nums) { Console.Write(a.ToString()); } }|] } } "; var queryOutput = @" using System; using System.Collections.Generic; using System.Linq; class A { public static implicit operator int(A x) { throw null; } public static implicit operator A(int x) { throw null; } } class B : A { } class C { void M(IEnumerable<int> nums) { foreach (var a in from B a in nums from A c in nums select a) { Console.Write(a.ToString()); } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Collections.Generic; using System.Linq; class A { public static implicit operator int(A x) { throw null; } public static implicit operator A(int x) { throw null; } } class B : A { } class C { void M(IEnumerable<int> nums) { foreach (var a in nums.SelectMany(a => nums.Select(c => a))) { Console.Write(a.ToString()); } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryInForEachWithSameVariableNameAndSameType() { var source = @" using System; using System.Collections.Generic; using System.Linq; class A { public static implicit operator int(A x) { throw null; } public static implicit operator A(int x) { throw null; } } class C { void M(IEnumerable<int> nums) { [|foreach (A a in nums) { foreach (A c in nums) { Console.Write(a.ToString()); } }|] } } "; var queryOutput = @" using System; using System.Collections.Generic; using System.Linq; class A { public static implicit operator int(A x) { throw null; } public static implicit operator A(int x) { throw null; } } class C { void M(IEnumerable<int> nums) { foreach (var a in from A a in nums from A c in nums select a) { Console.Write(a.ToString()); } } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Collections.Generic; using System.Linq; class A { public static implicit operator int(A x) { throw null; } public static implicit operator A(int x) { throw null; } } class C { void M(IEnumerable<int> nums) { foreach (var a in nums.SelectMany(a => nums.Select(c => a))) { Console.Write(a.ToString()); } } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task QueryInForEachWithConvertedType() { var source = @" using System; using System.Collections.Generic; static class Extensions { public static IEnumerable<C> Select(this int[] x, Func<int, C> predicate) => throw null; } class C { public static implicit operator int(C x) { throw null; } public static implicit operator C(int x) { throw null; } IEnumerable<C> Test() { [|foreach (var x in new[] { 1, 2, 3 }) { yield return x; }|] } } "; var queryOutput = @" using System; using System.Collections.Generic; using System.Linq; static class Extensions { public static IEnumerable<C> Select(this int[] x, Func<int, C> predicate) => throw null; } class C { public static implicit operator int(C x) { throw null; } public static implicit operator C(int x) { throw null; } IEnumerable<C> Test() { return from x in new[] { 1, 2, 3 } select x; } } "; await TestAsync(source, queryOutput, parseOptions: null); var linqInvocationOutput = @" using System; using System.Collections.Generic; using System.Linq; static class Extensions { public static IEnumerable<C> Select(this int[] x, Func<int, C> predicate) => throw null; } class C { public static implicit operator int(C x) { throw null; } public static implicit operator C(int x) { throw null; } IEnumerable<C> Test() { return new[] { 1, 2, 3 }; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task IQueryableConvertedToIEnumerableInReturn() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { [|foreach (int n1 in nums.AsQueryable()) { yield return n1; }|] yield break; } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return from int n1 in nums.AsQueryable() select n1; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return nums.AsQueryable(); } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ReturnIQueryableConvertedToIEnumerableInAssignment() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { [|foreach (int n1 in nums.AsQueryable()) { yield return n1; }|] } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return from int n1 in nums.AsQueryable() select n1; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return nums.AsQueryable(); } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } #endregion #region In ToList [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListLastDeclarationMerge() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list0 = new List<int>(), list = new List<int>(); [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list0 = new List<int>(); return (from int n1 in nums from int n2 in nums select n1).ToList(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list0 = new List<int>(); return (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListParameterizedConstructor() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>(nums); [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>(nums); list.AddRange(from int n1 in nums from int n2 in nums select n1); return list; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>(nums); list.AddRange(nums.SelectMany(n1 => nums.Select(n2 => n1))); return list; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListWithListInitializer() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>() { 1, 2, 3 }; [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>() { 1, 2, 3 }; list.AddRange(from int n1 in nums from int n2 in nums select n1); return list; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>() { 1, 2, 3 }; list.AddRange(nums.SelectMany(n1 => nums.Select(n2 => n1))); return list; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListWithEmptyArgumentList() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int> { }; [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { return (from int n1 in nums from int n2 in nums select n1).ToList(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { return (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListNotLastDeclaration() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>(), list1 = new List<int>(); [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>(), list1 = new List<int>(); list.AddRange(from int n1 in nums from int n2 in nums select n1); return list; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list = new List<int>(), list1 = new List<int>(); list.AddRange(nums.SelectMany(n1 => nums.Select(n2 => n1))); return list; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListAssignToParameter() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums, List<int> list) { list = new List<int>(); [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums, List<int> list) { list = (from int n1 in nums from int n2 in nums select n1).ToList(); return list; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums, List<int> list) { list = (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList(); return list; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListToArrayElement() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, List<int>[] lists) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { lists[0].Add(n1); } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, List<int>[] lists) { lists[0].AddRange(from int n1 in nums from int n2 in nums select n1); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, List<int>[] lists) { lists[0].AddRange(nums.SelectMany(n1 => nums.Select(n2 => n1))); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListToNewArrayElement() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, List<int>[] lists) { lists[0] = new List<int>(); [|foreach (int n1 in nums) { foreach (int n2 in nums) { lists[0].Add(n1); } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, List<int>[] lists) { lists[0] = (from int n1 in nums from int n2 in nums select n1).ToList(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, List<int>[] lists) { lists[0] = (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListHashSetNoConversion() { var source = @" using System.Collections.Generic; class C { void M(IEnumerable<int> nums) { var hashSet = new HashSet<int>(); [|foreach (int n1 in nums) { hashSet.Add(n1); }|] } } "; await TestMissingAsync(source); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListMergeWithReturn() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { var list = new List<int>(); [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { return (from int n1 in nums from int n2 in nums select n1).ToList(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { return (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListSeparateDeclarationAndAssignmentMergeWithReturn() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list; list = new List<int>(); [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list; return (from int n1 in nums from int n2 in nums select n1).ToList(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { List<int> list; return (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListSeparateDeclarationAndAssignment() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { List<int> list; list = new List<int>(); [|foreach (int n1 in nums) { foreach (int n2 in nums) { list.Add(n1); } }|] return list.Count; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { List<int> list; list = (from int n1 in nums from int n2 in nums select n1).ToList(); return list.Count; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { List<int> list; list = (nums.SelectMany(n1 => nums.Select(n2 => n1))).ToList(); return list.Count; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListTypeReplacement01() { var source = @" using System; using System.Linq; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C c3 = new C { 100, 200, 300 }; C r1 = new C(); [|foreach (int x in c1) { foreach (int y in c2) { foreach (int z in c3) { var g = x + y + z; if (x + y / 10 + z / 100 < 6) { r1.Add(g); } } } }|] Console.WriteLine(r1); } } "; var queryOutput = @" using System; using System.Linq; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C c3 = new C { 100, 200, 300 }; C r1 = (from int x in c1 from int y in c2 from int z in c3 let g = x + y + z where x + y / 10 + z / 100 < 6 select g).ToList(); Console.WriteLine(r1); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Linq; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C c3 = new C { 100, 200, 300 }; C r1 = new C(); foreach (var (x, y, z) in c1.SelectMany(x => c2.SelectMany(y => c3.Select(z => (x, y, z))))) { var g = x + y + z; if (x + y / 10 + z / 100 < 6) { r1.Add(g); } } Console.WriteLine(r1); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListTypeReplacement02() { var source = @" using System.Linq; using System; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C r1 = new C(); [|foreach (int x in c1) { foreach (var y in c2) { if (Equals(x, y / 10)) { var z = x + y; r1.Add(z); } } }|] Console.WriteLine(r1); } } "; var queryOutput = @" using System.Linq; using System; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C r1 = (from int x in c1 from y in c2 where Equals(x, y / 10) let z = x + y select z).ToList(); Console.WriteLine(r1); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Linq; using System; using C = System.Collections.Generic.List<int>; class Query { public static void Main(string[] args) { C c1 = new C { 1, 2, 3 }; C c2 = new C { 10, 20, 30 }; C r1 = new C(); foreach (var (x, y) in c1.SelectMany(x => c2.Where(y => Equals(x, y / 10)).Select(y => (x, y)))) { var z = x + y; r1.Add(z); } Console.WriteLine(r1); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListPropertyAssignment() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); c.A = new List<int>(); [|foreach (var x in nums) { c.A.Add(x + 1); }|] } class C { public List<int> A { get; set; } } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); c.A = (from x in nums select x + 1).ToList(); } class C { public List<int> A { get; set; } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; public class Test { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); c.A = (nums.Select(x => x + 1)).ToList(); } class C { public List<int> A { get; set; } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListPropertyAssignmentNoDeclaration() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { void M() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); [|foreach (var x in nums) { c.A.Add(x + 1); }|] } class C { public List<int> A { get; set; } } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; public class Test { void M() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); c.A.AddRange(from x in nums select x + 1); } class C { public List<int> A { get; set; } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; public class Test { void M() { var nums = new int[] { 1, 2, 3, 4 }; var c = new C(); c.A.AddRange(nums.Select(x => x + 1)); } class C { public List<int> A { get; set; } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListNoInitialization() { var source = @" using System.Collections.Generic; using System.Linq; public class Test { public List<int> A { get; set; } void M() { [|foreach (var x in new int[] { 1, 2, 3, 4 }) { A.Add(x + 1); }|] } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; public class Test { public List<int> A { get; set; } void M() { A.AddRange(from x in new int[] { 1, 2, 3, 4 } select x + 1); } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; public class Test { public List<int> A { get; set; } void M() { A.AddRange((new int[] { 1, 2, 3, 4 }).Select(x => x + 1)); } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task ToListOverride() { var source = @" using System.Collections.Generic; using System.Linq; public static class C { public static void Add<T>(this List<T> list, T value, T anotherValue) { } } public class Test { void M() { var list = new List<int>(); [|foreach (var x in new int[] { 1, 2, 3, 4 }) { list.Add(x + 1, x); }|] } }"; await TestMissingAsync(source); } #endregion #region In Count [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInMultipleDeclarationLast() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int i = 0, cnt = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int i = 0, cnt = (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int i = 0, cnt = (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInMultipleDeclarationNotLast() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int cnt = 0, i = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int cnt = 0, i = 0; cnt += (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int cnt = 0, i = 0; cnt += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInParameter() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { c++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c += (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInParameterAssignedToZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { c++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c = (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c = (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInParameterAssignedToNonZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c = 5; [|foreach (int n1 in nums) { foreach (int n2 in nums) { c++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c = 5; c += (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums, int c) { c = 5; c += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInDeclarationMergeToReturn() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { var cnt = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] return cnt; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { return (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { return (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInDeclarationConversion() { var source = @" using System.Collections.Generic; using System.Linq; class C { double M(IEnumerable<int> nums) { double c = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { c++; } }|] return c; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { double M(IEnumerable<int> nums) { return (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { double M(IEnumerable<int> nums) { return (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInMultipleDeclarationMergeToReturnLast() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int c = 0, cnt = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] return cnt; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int c = 0; return (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int c = 0; return (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInMultipleDeclarationLastButNotZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int c = 0, cnt = 5; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] return cnt; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int c = 0, cnt = 5; cnt += (from int n1 in nums from int n2 in nums select n1).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int c = 0, cnt = 5; cnt += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInMultipleDeclarationMergeToReturnNotLast() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt = 0, c = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] return cnt; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt = 0, c = 0; cnt += (from int n1 in nums from int n2 in nums select n1).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt = 0, c = 0; cnt += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInMultipleDeclarationNonZeroToReturnNotLast() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt = 5, c = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] return cnt; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt = 5, c = 0; cnt += (from int n1 in nums from int n2 in nums select n1).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt = 5, c = 0; cnt += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInAssignmentToZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt; cnt = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] return cnt; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt; return (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt; return (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInAssignmentToNonZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt; cnt = 5; [|foreach (int n1 in nums) { foreach (int n2 in nums) { cnt++; } }|] return cnt; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt; cnt = 5; cnt += (from int n1 in nums from int n2 in nums select n1).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { int cnt; cnt = 5; cnt += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); return cnt; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountInParameterAssignedToZeroAndReturned() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums, int c) { c = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { c++; } }|] return c; } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums, int c) { c = (from int n1 in nums from int n2 in nums select n1).Count(); return c; } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums, int c) { c = (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); return c; } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountDeclareWithNonZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var count = 5; [|foreach (int n1 in nums) { foreach (int n2 in nums) { count++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var count = 5; count += (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var count = 5; count += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountAssignWithZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int count = 1; count = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { count++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int count = 1; count = (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int count = 1; count = (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountAssignWithNonZero() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var count = 0; count = 4; [|foreach (int n1 in nums) { foreach (int n2 in nums) { count++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var count = 0; count = 4; count += (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { var count = 0; count = 4; count += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountAssignPropertyAssignedToZero() { var source = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B = 0; [|foreach (int n1 in nums) { foreach (int n2 in nums) { a.B++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B = (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B = (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountAssignPropertyAssignedToNonZero() { var source = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B = 5; [|foreach (int n1 in nums) { foreach (int n2 in nums) { a.B++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B = 5; a.B += (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B = 5; a.B += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountAssignPropertyNotKnownAssigned() { var source = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { [|foreach (int n1 in nums) { foreach (int n2 in nums) { a.B++; } }|] } } "; var queryOutput = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B += (from int n1 in nums from int n2 in nums select n1).Count(); } } "; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class A { public int B { get; set; }} class C { void M(IEnumerable<int> nums, A a) { a.B += (nums.SelectMany(n1 => nums.Select(n2 => n1))).Count(); } } "; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CountIQueryableInInvocation() { var source = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int c = 0; [|foreach (int n1 in nums.AsQueryable()) { c++; }|] } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int c = (from int n1 in nums.AsQueryable() select n1).Count(); } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { int c = (nums.AsQueryable()).Count(); } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } #endregion #region Comments [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CommentsYieldReturn() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { [|// 1 foreach /* 2 */( /* 3 */ var /* 4 */ x /* 5 */ in /* 6 */ nums /* 7 */)// 8 { // 9 /* 10 */ foreach /* 11 */ (/* 12 */ int /* 13 */ y /* 14 */ in /* 15 */ nums /* 16 */)/* 17 */ // 18 {// 19 /*20 */ if /* 21 */(/* 22 */ x > 2 /* 23 */) // 24 { // 25 /* 26 */ yield /* 27 */ return /* 28 */ x * y /* 29 */; // 30 /* 31 */ }// 32 /* 33 */ } // 34 /* 35 */ }|] /* 36 */ /* 37 */ yield /* 38 */ break/* 39*/; // 40 } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return // 25 // 1 from/* 3 *//* 2 *//* 4 */x /* 5 */ in/* 6 */nums/* 7 */// 8 // 9 /* 10 */ from/* 12 *//* 11 */int /* 13 */ y /* 14 */ in/* 15 */nums/* 16 *//* 17 */// 18 // 19 /*20 */ where/* 21 *//* 22 */x > 2/* 23 */// 24 /* 26 *//* 27 *//* 28 */ select x * y/* 29 *//* 31 */// 32 /* 33 */// 34 /* 35 *//* 36 */// 30 /* 37 *//* 38 *//* 39*/// 40 ; } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { return nums /* 7 */.SelectMany( // 1 /* 2 */// 25 /* 4 */x /* 5 */ => nums /* 16 */.Where( /*20 *//* 21 */// 19 y => /* 22 */x > 2/* 23 */// 24 ).Select( // 9 /* 10 *//* 11 *//* 13 */y /* 14 */ => /* 26 *//* 27 *//* 28 */x * y/* 29 *//* 31 */// 32 /* 33 */// 34 /* 35 *//* 36 */// 30 /* 37 *//* 38 *//* 39*/// 40 /* 12 *//* 15 *//* 17 */// 18 )/* 3 *//* 6 */// 8 ); } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CommentsToList() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { /* 1 */ var /* 2 */ list /* 3 */ = /* 4 */ new List<int>(); // 5 /* 6 */ [|foreach /* 7 */ (/* 8 */ var /* 9 */ x /* 10 */ in /* 11 */ nums /* 12 */) // 13 /* 14 */{ // 15 /* 16 */var /* 17 */ y /* 18 */ = /* 19 */ x + 1 /* 20 */; //21 /* 22 */ list.Add(/* 23 */y /* 24 */) /* 25 */;//26 /*27*/} //28|] /*29*/return /*30*/ list /*31*/; //32 } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { /*29*/ return /*30*/ /* 1 *//* 2 *//* 3 *//* 4 */// 5 /*31*/ ( /* 6 */from/* 8 *//* 7 *//* 9 */x /* 10 */ in/* 11 */nums/* 12 */// 13 /* 14 */// 15 /* 16 *//* 17 */ let y /* 18 */ = /* 19 */ x + 1/* 20 *///21 select y/* 24 *//*27*///28 ).ToList()/* 22 *//* 23 *//* 25 *///26 ; //32 } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); // No linq refactoring offered due to variable declaration in outermost foreach. await TestActionCountAsync(source, count: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CommentsToList_02() { var source = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { /* 1 */ var /* 2 */ list /* 3 */ = /* 4 */ new List<int>(); // 5 /* 6 */ [|foreach /* 7 */ (/* 8 */ var /* 9 */ x /* 10 */ in /* 11 */ nums /* 12 */) // 13 /* 14 */{ // 15 /* 16 */ list.Add(/* 17 */ x + 1 /* 18 */) /* 19 */;//20 /*21*/} //22|] /*23*/return /*24*/ list /*25*/; //26 } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { /*23*/ return /*24*/ /* 1 *//* 2 *//* 3 *//* 4 */// 5 /*25*/ ( /* 14 */// 15 /* 6 */from/* 8 *//* 7 *//* 9 */x /* 10 */ in/* 11 */nums/* 12 */// 13 select x + 1/* 18 *//*21*///22 ).ToList()/* 16 *//* 17 *//* 19 *///20 ; //26 } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { List<int> M(IEnumerable<int> nums) { /*23*/ return /*24*/ /* 1 *//* 2 *//* 3 *//* 4 */// 5 /*25*/ (nums /* 12 */.Select( /* 6 *//* 7 *//* 14 */// 15 /* 9 */x /* 10 */ => x + 1/* 18 *//*21*///22 /* 8 *//* 11 */// 13 )).ToList()/* 16 *//* 17 *//* 19 *///20 ; //26 } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CommentsCount() { var source = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { /* 1 */ var /* 2 */ c /* 3 */ = /* 4 */ 0; // 5 /* 6 */ [| foreach /* 7 */ (/* 8 */ var /* 9 */ x /* 10 */ in /* 11 */ nums /* 12 */) // 13 /* 14 */{ // 15 /* 16 */ c++ /* 17 */;//18 /*19*/}|] //20 /*21*/return /*22*/ c /*23*/; //24 } }"; var queryOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { /*21*/ return /*22*/ /* 1 *//* 2 *//* 3 *//* 4 */// 5 /*23*/ ( /* 14 */// 15 /* 6 */from/* 8 *//* 7 *//* 9 */x /* 10 */ in/* 11 */nums/* 12 */// 13 select x/* 10 *//*19*///20 ).Count()/* 16 *//* 17 *///18 ; //24 } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System.Collections.Generic; using System.Linq; class C { int M(IEnumerable<int> nums) { /*21*/ return /*22*/ /* 1 *//* 2 *//* 3 *//* 4 */// 5 /*23*/ (nums /* 12 *//* 6 *//* 7 *//* 14 */// 15 /* 9 *//* 10 *//* 10 *//*19*///20 /* 8 *//* 11 */// 13 ).Count()/* 16 *//* 17 *///18 ; //24 } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CommentsDefault() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { [|/* 1 */ foreach /* 2 */(int /* 3 */ n1 /* 4 */in /* 5 */ nums /* 6 */)// 7 /* 8*/{// 9 /* 10 */int /* 11 */ a /* 12 */ = /* 13 */ n1 + n1 /* 14*/, /* 15 */ b /*16*/ = /*17*/ n1 * n1/*18*/;//19 /*20*/Console.WriteLine(a + b);//21 /*22*/}/*23*/|] } }"; var queryOutput = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var (a /* 12 */ , b /*16*/ ) in /* 1 */from/* 2 */int /* 3 */ n1 /* 4 */in/* 5 */nums/* 6 */// 7 /* 8*/// 9 /* 10 *//* 11 */ let a /* 12 */ = /* 13 */ n1 + n1/* 14*//* 15 */ let b /*16*/ = /*17*/ n1 * n1/*18*///19 select (a /* 12 */ , b /*16*/ )/*22*//*23*/) { /*20*/ Console.WriteLine(a + b);//21 } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); // No linq refactoring offered due to variable declaration(s) in outermost foreach. await TestActionCountAsync(source, count: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task CommentsDefault_02() { var source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { [|/* 1 */ foreach /* 2 */(int /* 3 */ n1 /* 4 */in /* 5 */ nums /* 6 */)// 7 /* 8*/{// 9 /* 10 */ if /* 11 */ (/* 12 */ n1 /* 13 */ > /* 14 */ 0/* 15 */ ) // 16 /* 17 */{ // 18 /*19*/Console.WriteLine(n1);//20 /* 21 */} // 22 /*23*/}/*24*/|] } }"; var queryOutput = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var n1 /* 4 */in /* 17 */// 18 /* 1 */from/* 2 */int /* 3 */ n1 /* 4 */in/* 5 */nums/* 6 */// 7 /* 8*/// 9 /* 10 */ where/* 11 *//* 12 */n1 /* 13 */ > /* 14 */ 0/* 15 */// 16 select n1/* 4 *//* 21 */// 22 /*23*//*24*/ ) { /*19*/ Console.WriteLine(n1);//20 } } }"; await TestInRegularAndScriptAsync(source, queryOutput, index: 0); var linqInvocationOutput = @" using System; using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<int> nums) { foreach (var n1 /* 4 */in nums /* 6 */.Where( /* 10 *//* 11 *//* 8*/// 9 n1 => /* 12 */n1 /* 13 */ > /* 14 */ 0/* 15 */// 16 ) /* 1 *//* 2 *//* 17 */// 18 /* 3 *//* 4 *//* 4 *//* 21 */// 22 /*23*//*24*//* 5 */// 7 ) { /*19*/ Console.WriteLine(n1);//20 } } }"; await TestInRegularAndScriptAsync(source, linqInvocationOutput, index: 1); } #endregion #region Preprocessor directives [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToQuery)] public async Task NoConversionPreprocessorDirectives() { var source = @" using System.Collections.Generic; using System.Linq; class C { IEnumerable<int> M(IEnumerable<int> nums) { [|foreach(var x in nums) { #if (true) yield return x + 1; #endif }|] } }"; // Cannot convert expressions with preprocessor directives await TestMissingAsync(source); } #endregion } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/IntegrationTest/TestUtilities/InProcess/CSharpInteractiveWindow_InProc.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.VisualStudio.InteractiveWindow; using Microsoft.VisualStudio.LanguageServices.CSharp.Interactive; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess { internal class CSharpInteractiveWindow_InProc : InteractiveWindow_InProc { private const string ViewCommand = "View.C#Interactive"; private CSharpInteractiveWindow_InProc() : base(ViewCommand, CSharpVsInteractiveWindowPackage.Id) { } public static CSharpInteractiveWindow_InProc Create() => new CSharpInteractiveWindow_InProc(); protected override IInteractiveWindow AcquireInteractiveWindow() => InvokeOnUIThread(cancellationToken => { var componentModel = GetComponentModel(); var vsInteractiveWindowProvider = componentModel.GetService<CSharpVsInteractiveWindowProvider>(); var vsInteractiveWindow = vsInteractiveWindowProvider.Open(instanceId: 0, focus: true); return vsInteractiveWindow.InteractiveWindow; }); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.VisualStudio.InteractiveWindow; using Microsoft.VisualStudio.LanguageServices.CSharp.Interactive; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess { internal class CSharpInteractiveWindow_InProc : InteractiveWindow_InProc { private const string ViewCommand = "View.C#Interactive"; private CSharpInteractiveWindow_InProc() : base(ViewCommand, CSharpVsInteractiveWindowPackage.Id) { } public static CSharpInteractiveWindow_InProc Create() => new CSharpInteractiveWindow_InProc(); protected override IInteractiveWindow AcquireInteractiveWindow() => InvokeOnUIThread(cancellationToken => { var componentModel = GetComponentModel(); var vsInteractiveWindowProvider = componentModel.GetService<CSharpVsInteractiveWindowProvider>(); var vsInteractiveWindow = vsInteractiveWindowProvider.Open(instanceId: 0, focus: true); return vsInteractiveWindow.InteractiveWindow; }); } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/Shared/Extensions/ISymbolExtensions.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; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Threading; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Shared.Utilities.EditorBrowsableHelpers; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class ISymbolExtensions { public static DeclarationModifiers GetSymbolModifiers(this ISymbol symbol) { return new DeclarationModifiers( isStatic: symbol.IsStatic, isAbstract: symbol.IsAbstract, isUnsafe: symbol.RequiresUnsafeModifier(), isVirtual: symbol.IsVirtual, isOverride: symbol.IsOverride, isSealed: symbol.IsSealed); } /// <summary> /// Checks a given symbol for browsability based on its declaration location, attributes /// explicitly limiting browsability, and whether showing of advanced members is enabled. /// The optional editorBrowsableInfo parameters may be used to specify the symbols of the /// constructors of the various browsability limiting attributes because finding these /// repeatedly over a large list of symbols can be slow. If these are not provided, /// they will be found in the compilation. /// </summary> public static bool IsEditorBrowsable( this ISymbol symbol, bool hideAdvancedMembers, Compilation compilation, EditorBrowsableInfo editorBrowsableInfo = default) { return IsEditorBrowsableWithState( symbol, hideAdvancedMembers, compilation, editorBrowsableInfo).isBrowsable; } // In addition to given symbol's browsability, also returns its EditorBrowsableState if it contains EditorBrowsableAttribute. public static (bool isBrowsable, bool isEditorBrowsableStateAdvanced) IsEditorBrowsableWithState( this ISymbol symbol, bool hideAdvancedMembers, Compilation compilation, EditorBrowsableInfo editorBrowsableInfo = default) { // Namespaces can't have attributes, so just return true here. This also saves us a // costly check if this namespace has any locations in source (since a merged namespace // needs to go collect all the locations). if (symbol.Kind == SymbolKind.Namespace) { return (isBrowsable: true, isEditorBrowsableStateAdvanced: false); } // check for IsImplicitlyDeclared so we don't spend time examining VB's embedded types. // This saves a few percent in typing scenarios. An implicitly declared symbol can't // have attributes, so it can't be hidden by them. if (symbol.IsImplicitlyDeclared) { return (isBrowsable: true, isEditorBrowsableStateAdvanced: false); } if (editorBrowsableInfo.IsDefault) { editorBrowsableInfo = new EditorBrowsableInfo(compilation); } // Ignore browsability limiting attributes if the symbol is declared in source. // Check all locations since some of VB's embedded My symbols are declared in // both source and the MyTemplateLocation. if (symbol.Locations.All(loc => loc.IsInSource)) { // The HideModuleNameAttribute still applies to Modules defined in source return (!IsBrowsingProhibitedByHideModuleNameAttribute(symbol, editorBrowsableInfo.HideModuleNameAttribute), isEditorBrowsableStateAdvanced: false); } var (isProhibited, isEditorBrowsableStateAdvanced) = IsBrowsingProhibited(symbol, hideAdvancedMembers, editorBrowsableInfo); return (!isProhibited, isEditorBrowsableStateAdvanced); } private static (bool isProhibited, bool isEditorBrowsableStateAdvanced) IsBrowsingProhibited( ISymbol symbol, bool hideAdvancedMembers, EditorBrowsableInfo editorBrowsableInfo) { var attributes = symbol.GetAttributes(); if (attributes.Length == 0) { return (isProhibited: false, isEditorBrowsableStateAdvanced: false); } var (isProhibited, isEditorBrowsableStateAdvanced) = IsBrowsingProhibitedByEditorBrowsableAttribute(attributes, hideAdvancedMembers, editorBrowsableInfo.EditorBrowsableAttributeConstructor); return ((isProhibited || IsBrowsingProhibitedByTypeLibTypeAttribute(attributes, editorBrowsableInfo.TypeLibTypeAttributeConstructors) || IsBrowsingProhibitedByTypeLibFuncAttribute(attributes, editorBrowsableInfo.TypeLibFuncAttributeConstructors) || IsBrowsingProhibitedByTypeLibVarAttribute(attributes, editorBrowsableInfo.TypeLibVarAttributeConstructors) || IsBrowsingProhibitedByHideModuleNameAttribute(symbol, editorBrowsableInfo.HideModuleNameAttribute, attributes)), isEditorBrowsableStateAdvanced); } private static bool IsBrowsingProhibitedByHideModuleNameAttribute( ISymbol symbol, INamedTypeSymbol? hideModuleNameAttribute, ImmutableArray<AttributeData> attributes = default) { if (hideModuleNameAttribute == null || !symbol.IsModuleType()) { return false; } attributes = attributes.IsDefault ? symbol.GetAttributes() : attributes; foreach (var attribute in attributes) { if (Equals(attribute.AttributeClass, hideModuleNameAttribute)) { return true; } } return false; } private static (bool isProhibited, bool isEditorBrowsableStateAdvanced) IsBrowsingProhibitedByEditorBrowsableAttribute( ImmutableArray<AttributeData> attributes, bool hideAdvancedMembers, IMethodSymbol? constructor) { if (constructor == null) { return (isProhibited: false, isEditorBrowsableStateAdvanced: false); } foreach (var attribute in attributes) { if (Equals(attribute.AttributeConstructor, constructor) && attribute.ConstructorArguments.Length == 1 && attribute.ConstructorArguments.First().Value is int) { #nullable disable // Should use unboxed value from previous 'is int' https://github.com/dotnet/roslyn/issues/39166 var state = (EditorBrowsableState)attribute.ConstructorArguments.First().Value; #nullable enable if (EditorBrowsableState.Never == state) { return (isProhibited: true, isEditorBrowsableStateAdvanced: false); } if (EditorBrowsableState.Advanced == state) { return (isProhibited: hideAdvancedMembers, isEditorBrowsableStateAdvanced: true); } } } return (isProhibited: false, isEditorBrowsableStateAdvanced: false); } private static bool IsBrowsingProhibitedByTypeLibTypeAttribute( ImmutableArray<AttributeData> attributes, ImmutableArray<IMethodSymbol> constructors) { return IsBrowsingProhibitedByTypeLibAttributeWorker( attributes, constructors, TypeLibTypeFlagsFHidden); } private static bool IsBrowsingProhibitedByTypeLibFuncAttribute( ImmutableArray<AttributeData> attributes, ImmutableArray<IMethodSymbol> constructors) { return IsBrowsingProhibitedByTypeLibAttributeWorker( attributes, constructors, TypeLibFuncFlagsFHidden); } private static bool IsBrowsingProhibitedByTypeLibVarAttribute( ImmutableArray<AttributeData> attributes, ImmutableArray<IMethodSymbol> constructors) { return IsBrowsingProhibitedByTypeLibAttributeWorker( attributes, constructors, TypeLibVarFlagsFHidden); } private const int TypeLibTypeFlagsFHidden = 0x0010; private const int TypeLibFuncFlagsFHidden = 0x0040; private const int TypeLibVarFlagsFHidden = 0x0040; private static bool IsBrowsingProhibitedByTypeLibAttributeWorker( ImmutableArray<AttributeData> attributes, ImmutableArray<IMethodSymbol> attributeConstructors, int hiddenFlag) { foreach (var attribute in attributes) { if (attribute.ConstructorArguments.Length == 1) { foreach (var constructor in attributeConstructors) { if (Equals(attribute.AttributeConstructor, constructor)) { // Check for both constructor signatures. The constructor that takes a TypeLib*Flags reports an int argument. var argumentValue = attribute.ConstructorArguments.First().Value; int actualFlags; if (argumentValue is int i) { actualFlags = i; } else if (argumentValue is short sh) { actualFlags = sh; } else { continue; } if ((actualFlags & hiddenFlag) == hiddenFlag) { return true; } } } } } return false; } public static DocumentationComment GetDocumentationComment(this ISymbol symbol, Compilation compilation, CultureInfo? preferredCulture = null, bool expandIncludes = false, bool expandInheritdoc = false, CancellationToken cancellationToken = default) => GetDocumentationComment(symbol, visitedSymbols: null, compilation, preferredCulture, expandIncludes, expandInheritdoc, cancellationToken); private static DocumentationComment GetDocumentationComment(ISymbol symbol, HashSet<ISymbol>? visitedSymbols, Compilation compilation, CultureInfo? preferredCulture, bool expandIncludes, bool expandInheritdoc, CancellationToken cancellationToken) { var xmlText = symbol.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); if (expandInheritdoc) { if (string.IsNullOrEmpty(xmlText)) { if (IsEligibleForAutomaticInheritdoc(symbol)) { xmlText = $@"<doc><inheritdoc/></doc>"; } else { return DocumentationComment.Empty; } } try { var element = XElement.Parse(xmlText, LoadOptions.PreserveWhitespace); element.ReplaceNodes(RewriteMany(symbol, visitedSymbols, compilation, element.Nodes().ToArray(), cancellationToken)); xmlText = element.ToString(SaveOptions.DisableFormatting); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { } } return RoslynString.IsNullOrEmpty(xmlText) ? DocumentationComment.Empty : DocumentationComment.FromXmlFragment(xmlText); static bool IsEligibleForAutomaticInheritdoc(ISymbol symbol) { // Only the following symbols are eligible to inherit documentation without an <inheritdoc/> element: // // * Members that override an inherited member // * Members that implement an interface member if (symbol.IsOverride) { return true; } if (symbol.ContainingType is null) { // Observed with certain implicit operators, such as operator==(void*, void*). return false; } switch (symbol.Kind) { case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.Event: if (symbol.ExplicitOrImplicitInterfaceImplementations().Any()) { return true; } break; default: break; } return false; } } private static XNode[] RewriteInheritdocElements(ISymbol symbol, HashSet<ISymbol>? visitedSymbols, Compilation compilation, XNode node, CancellationToken cancellationToken) { if (node.NodeType == XmlNodeType.Element) { var element = (XElement)node; if (ElementNameIs(element, DocumentationCommentXmlNames.InheritdocElementName)) { var rewritten = RewriteInheritdocElement(symbol, visitedSymbols, compilation, element, cancellationToken); if (rewritten is object) { return rewritten; } } } var container = node as XContainer; if (container == null) { return new XNode[] { Copy(node, copyAttributeAnnotations: false) }; } var oldNodes = container.Nodes(); // Do this after grabbing the nodes, so we don't see copies of them. container = Copy(container, copyAttributeAnnotations: false); // WARN: don't use node after this point - use container since it's already been copied. if (oldNodes != null) { var rewritten = RewriteMany(symbol, visitedSymbols, compilation, oldNodes.ToArray(), cancellationToken); container.ReplaceNodes(rewritten); } return new XNode[] { container }; } private static XNode[] RewriteMany(ISymbol symbol, HashSet<ISymbol>? visitedSymbols, Compilation compilation, XNode[] nodes, CancellationToken cancellationToken) { var result = new List<XNode>(); foreach (var child in nodes) { result.AddRange(RewriteInheritdocElements(symbol, visitedSymbols, compilation, child, cancellationToken)); } return result.ToArray(); } private static XNode[]? RewriteInheritdocElement(ISymbol memberSymbol, HashSet<ISymbol>? visitedSymbols, Compilation compilation, XElement element, CancellationToken cancellationToken) { var crefAttribute = element.Attribute(XName.Get(DocumentationCommentXmlNames.CrefAttributeName)); var pathAttribute = element.Attribute(XName.Get(DocumentationCommentXmlNames.PathAttributeName)); var candidate = GetCandidateSymbol(memberSymbol); var hasCandidateCref = candidate is object; var hasCrefAttribute = crefAttribute is object; var hasPathAttribute = pathAttribute is object; if (!hasCrefAttribute && !hasCandidateCref) { // No cref available return null; } ISymbol? symbol; if (crefAttribute is null) { Contract.ThrowIfNull(candidate); symbol = candidate; } else { var crefValue = crefAttribute.Value; symbol = DocumentationCommentId.GetFirstSymbolForDeclarationId(crefValue, compilation); if (symbol is null) { return null; } } visitedSymbols ??= new HashSet<ISymbol>(); if (!visitedSymbols.Add(symbol)) { // Prevent recursion return null; } try { var inheritedDocumentation = GetDocumentationComment(symbol, visitedSymbols, compilation, preferredCulture: null, expandIncludes: true, expandInheritdoc: true, cancellationToken); if (inheritedDocumentation == DocumentationComment.Empty) { return Array.Empty<XNode>(); } var document = XDocument.Parse(inheritedDocumentation.FullXmlFragment); string xpathValue; if (string.IsNullOrEmpty(pathAttribute?.Value)) { xpathValue = BuildXPathForElement(element.Parent!); } else { xpathValue = pathAttribute!.Value; if (xpathValue.StartsWith("/")) { // Account for the root <doc> or <member> element xpathValue = "/*" + xpathValue; } } // Consider the following code, we want Test<int>.Clone to say "Clones a Test<int>" instead of "Clones a int", thus // we rewrite `typeparamref`s as cref pointing to the correct type: /* public class Test<T> : ICloneable<Test<T>> { /// <inheritdoc/> public Test<T> Clone() => new(); } /// <summary>A type that has clonable instances.</summary> /// <typeparam name="T">The type of instances that can be cloned.</typeparam> public interface ICloneable<T> { /// <summary>Clones a <typeparamref name="T"/>.</summary> public T Clone(); } */ // Note: there is no way to cref an instantiated generic type. See https://github.com/dotnet/csharplang/issues/401 var typeParameterRefs = document.Descendants(DocumentationCommentXmlNames.TypeParameterReferenceElementName).ToImmutableArray(); foreach (var typeParameterRef in typeParameterRefs) { if (typeParameterRef.Attribute(DocumentationCommentXmlNames.NameAttributeName) is var typeParamName) { var index = symbol.OriginalDefinition.GetAllTypeParameters().IndexOf(p => p.Name == typeParamName.Value); if (index >= 0) { var typeArgs = symbol.GetAllTypeArguments(); if (index < typeArgs.Length) { var docId = typeArgs[index].GetDocumentationCommentId(); var replacement = new XElement(DocumentationCommentXmlNames.SeeElementName); replacement.SetAttributeValue(DocumentationCommentXmlNames.CrefAttributeName, docId); typeParameterRef.ReplaceWith(replacement); } } } } var loadedElements = TrySelectNodes(document, xpathValue); return loadedElements ?? Array.Empty<XNode>(); } catch (XmlException) { return Array.Empty<XNode>(); } finally { visitedSymbols.Remove(symbol); } // Local functions static ISymbol? GetCandidateSymbol(ISymbol memberSymbol) { if (memberSymbol.ExplicitInterfaceImplementations().Any()) { return memberSymbol.ExplicitInterfaceImplementations().First(); } else if (memberSymbol.IsOverride) { return memberSymbol.GetOverriddenMember(); } if (memberSymbol is IMethodSymbol methodSymbol) { if (methodSymbol.MethodKind == MethodKind.Constructor || methodSymbol.MethodKind == MethodKind.StaticConstructor) { var baseType = memberSymbol.ContainingType.BaseType; #nullable disable // Can 'baseType' be null here? https://github.com/dotnet/roslyn/issues/39166 return baseType.Constructors.Where(c => IsSameSignature(methodSymbol, c)).FirstOrDefault(); #nullable enable } else { // check for implicit interface return methodSymbol.ExplicitOrImplicitInterfaceImplementations().FirstOrDefault(); } } else if (memberSymbol is INamedTypeSymbol typeSymbol) { if (typeSymbol.TypeKind == TypeKind.Class) { // Classes use the base type as the default inheritance candidate. A different target (e.g. an // interface) can be provided via the 'path' attribute. return typeSymbol.BaseType; } else if (typeSymbol.TypeKind == TypeKind.Interface) { return typeSymbol.Interfaces.FirstOrDefault(); } else { // This includes structs, enums, and delegates as mentioned in the inheritdoc spec return null; } } return memberSymbol.ExplicitOrImplicitInterfaceImplementations().FirstOrDefault(); } static bool IsSameSignature(IMethodSymbol left, IMethodSymbol right) { if (left.Parameters.Length != right.Parameters.Length) { return false; } if (left.IsStatic != right.IsStatic) { return false; } if (!left.ReturnType.Equals(right.ReturnType)) { return false; } for (var i = 0; i < left.Parameters.Length; i++) { if (!left.Parameters[i].Type.Equals(right.Parameters[i].Type)) { return false; } } return true; } static string BuildXPathForElement(XElement element) { if (ElementNameIs(element, "member") || ElementNameIs(element, "doc")) { // Avoid string concatenation allocations for inheritdoc as a top-level element return "/*/node()[not(self::overloads)]"; } var path = "/node()[not(self::overloads)]"; for (var current = element; current != null; current = current.Parent) { var currentName = current.Name.ToString(); if (ElementNameIs(current, "member") || ElementNameIs(current, "doc")) { // Allow <member> and <doc> to be used interchangeably currentName = "*"; } path = "/" + currentName + path; } return path; } } private static TNode Copy<TNode>(TNode node, bool copyAttributeAnnotations) where TNode : XNode { XNode copy; // Documents can't be added to containers, so our usual copy trick won't work. if (node.NodeType == XmlNodeType.Document) { copy = new XDocument(((XDocument)(object)node)); } else { XContainer temp = new XElement("temp"); temp.Add(node); copy = temp.LastNode!; temp.RemoveNodes(); } Debug.Assert(copy != node); Debug.Assert(copy.Parent == null); // Otherwise, when we give it one, it will be copied. // Copy annotations, the above doesn't preserve them. // We need to preserve Location annotations as well as line position annotations. CopyAnnotations(node, copy); // We also need to preserve line position annotations for all attributes // since we report errors with attribute locations. if (copyAttributeAnnotations && node.NodeType == XmlNodeType.Element) { var sourceElement = (XElement)(object)node; var targetElement = (XElement)copy; var sourceAttributes = sourceElement.Attributes().GetEnumerator(); var targetAttributes = targetElement.Attributes().GetEnumerator(); while (sourceAttributes.MoveNext() && targetAttributes.MoveNext()) { Debug.Assert(sourceAttributes.Current.Name == targetAttributes.Current.Name); CopyAnnotations(sourceAttributes.Current, targetAttributes.Current); } } return (TNode)copy; } private static void CopyAnnotations(XObject source, XObject target) { foreach (var annotation in source.Annotations<object>()) { target.AddAnnotation(annotation); } } private static XNode[]? TrySelectNodes(XNode node, string xpath) { try { var xpathResult = (IEnumerable)System.Xml.XPath.Extensions.XPathEvaluate(node, xpath); // Throws InvalidOperationException if the result of the XPath is an XDocument: return xpathResult?.Cast<XNode>().ToArray(); } catch (InvalidOperationException) { return null; } catch (XPathException) { return null; } } private static bool ElementNameIs(XElement element, string name) => string.IsNullOrEmpty(element.Name.NamespaceName) && DocumentationCommentXmlNames.ElementEquals(element.Name.LocalName, name); /// <summary> /// First, remove symbols from the set if they are overridden by other symbols in the set. /// If a symbol is overridden only by symbols outside of the set, then it is not removed. /// This is useful for filtering out symbols that cannot be accessed in a given context due /// to the existence of overriding members. Second, remove remaining symbols that are /// unsupported (e.g. pointer types in VB) or not editor browsable based on the EditorBrowsable /// attribute. /// </summary> public static ImmutableArray<T> FilterToVisibleAndBrowsableSymbols<T>( this ImmutableArray<T> symbols, bool hideAdvancedMembers, Compilation compilation) where T : ISymbol { symbols = symbols.RemoveOverriddenSymbolsWithinSet(); // Since all symbols are from the same compilation, find the required attribute // constructors once and reuse. var editorBrowsableInfo = new EditorBrowsableInfo(compilation); // PERF: HasUnsupportedMetadata may require recreating the syntax tree to get the base class, so first // check to see if we're referencing a symbol defined in source. static bool isSymbolDefinedInSource(Location l) => l.IsInSource; return symbols.WhereAsArray((s, arg) => (s.Locations.Any(isSymbolDefinedInSource) || !s.HasUnsupportedMetadata) && !s.IsDestructor() && s.IsEditorBrowsable( arg.hideAdvancedMembers, arg.editorBrowsableInfo.Compilation, arg.editorBrowsableInfo), (hideAdvancedMembers, editorBrowsableInfo)); } private static ImmutableArray<T> RemoveOverriddenSymbolsWithinSet<T>(this ImmutableArray<T> symbols) where T : ISymbol { var overriddenSymbols = new HashSet<ISymbol>(); foreach (var symbol in symbols) { var overriddenMember = symbol.GetOverriddenMember(); if (overriddenMember != null && !overriddenSymbols.Contains(overriddenMember)) overriddenSymbols.Add(overriddenMember); } return symbols.WhereAsArray(s => !overriddenSymbols.Contains(s)); } public static ImmutableArray<T> FilterToVisibleAndBrowsableSymbolsAndNotUnsafeSymbols<T>( this ImmutableArray<T> symbols, bool hideAdvancedMembers, Compilation compilation) where T : ISymbol { return symbols.FilterToVisibleAndBrowsableSymbols(hideAdvancedMembers, compilation) .WhereAsArray(s => !s.RequiresUnsafeModifier()); } } }
// Licensed to the .NET Foundation under one or more 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; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Threading; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Shared.Utilities.EditorBrowsableHelpers; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class ISymbolExtensions { public static DeclarationModifiers GetSymbolModifiers(this ISymbol symbol) { return new DeclarationModifiers( isStatic: symbol.IsStatic, isAbstract: symbol.IsAbstract, isUnsafe: symbol.RequiresUnsafeModifier(), isVirtual: symbol.IsVirtual, isOverride: symbol.IsOverride, isSealed: symbol.IsSealed); } /// <summary> /// Checks a given symbol for browsability based on its declaration location, attributes /// explicitly limiting browsability, and whether showing of advanced members is enabled. /// The optional editorBrowsableInfo parameters may be used to specify the symbols of the /// constructors of the various browsability limiting attributes because finding these /// repeatedly over a large list of symbols can be slow. If these are not provided, /// they will be found in the compilation. /// </summary> public static bool IsEditorBrowsable( this ISymbol symbol, bool hideAdvancedMembers, Compilation compilation, EditorBrowsableInfo editorBrowsableInfo = default) { return IsEditorBrowsableWithState( symbol, hideAdvancedMembers, compilation, editorBrowsableInfo).isBrowsable; } // In addition to given symbol's browsability, also returns its EditorBrowsableState if it contains EditorBrowsableAttribute. public static (bool isBrowsable, bool isEditorBrowsableStateAdvanced) IsEditorBrowsableWithState( this ISymbol symbol, bool hideAdvancedMembers, Compilation compilation, EditorBrowsableInfo editorBrowsableInfo = default) { // Namespaces can't have attributes, so just return true here. This also saves us a // costly check if this namespace has any locations in source (since a merged namespace // needs to go collect all the locations). if (symbol.Kind == SymbolKind.Namespace) { return (isBrowsable: true, isEditorBrowsableStateAdvanced: false); } // check for IsImplicitlyDeclared so we don't spend time examining VB's embedded types. // This saves a few percent in typing scenarios. An implicitly declared symbol can't // have attributes, so it can't be hidden by them. if (symbol.IsImplicitlyDeclared) { return (isBrowsable: true, isEditorBrowsableStateAdvanced: false); } if (editorBrowsableInfo.IsDefault) { editorBrowsableInfo = new EditorBrowsableInfo(compilation); } // Ignore browsability limiting attributes if the symbol is declared in source. // Check all locations since some of VB's embedded My symbols are declared in // both source and the MyTemplateLocation. if (symbol.Locations.All(loc => loc.IsInSource)) { // The HideModuleNameAttribute still applies to Modules defined in source return (!IsBrowsingProhibitedByHideModuleNameAttribute(symbol, editorBrowsableInfo.HideModuleNameAttribute), isEditorBrowsableStateAdvanced: false); } var (isProhibited, isEditorBrowsableStateAdvanced) = IsBrowsingProhibited(symbol, hideAdvancedMembers, editorBrowsableInfo); return (!isProhibited, isEditorBrowsableStateAdvanced); } private static (bool isProhibited, bool isEditorBrowsableStateAdvanced) IsBrowsingProhibited( ISymbol symbol, bool hideAdvancedMembers, EditorBrowsableInfo editorBrowsableInfo) { var attributes = symbol.GetAttributes(); if (attributes.Length == 0) { return (isProhibited: false, isEditorBrowsableStateAdvanced: false); } var (isProhibited, isEditorBrowsableStateAdvanced) = IsBrowsingProhibitedByEditorBrowsableAttribute(attributes, hideAdvancedMembers, editorBrowsableInfo.EditorBrowsableAttributeConstructor); return ((isProhibited || IsBrowsingProhibitedByTypeLibTypeAttribute(attributes, editorBrowsableInfo.TypeLibTypeAttributeConstructors) || IsBrowsingProhibitedByTypeLibFuncAttribute(attributes, editorBrowsableInfo.TypeLibFuncAttributeConstructors) || IsBrowsingProhibitedByTypeLibVarAttribute(attributes, editorBrowsableInfo.TypeLibVarAttributeConstructors) || IsBrowsingProhibitedByHideModuleNameAttribute(symbol, editorBrowsableInfo.HideModuleNameAttribute, attributes)), isEditorBrowsableStateAdvanced); } private static bool IsBrowsingProhibitedByHideModuleNameAttribute( ISymbol symbol, INamedTypeSymbol? hideModuleNameAttribute, ImmutableArray<AttributeData> attributes = default) { if (hideModuleNameAttribute == null || !symbol.IsModuleType()) { return false; } attributes = attributes.IsDefault ? symbol.GetAttributes() : attributes; foreach (var attribute in attributes) { if (Equals(attribute.AttributeClass, hideModuleNameAttribute)) { return true; } } return false; } private static (bool isProhibited, bool isEditorBrowsableStateAdvanced) IsBrowsingProhibitedByEditorBrowsableAttribute( ImmutableArray<AttributeData> attributes, bool hideAdvancedMembers, IMethodSymbol? constructor) { if (constructor == null) { return (isProhibited: false, isEditorBrowsableStateAdvanced: false); } foreach (var attribute in attributes) { if (Equals(attribute.AttributeConstructor, constructor) && attribute.ConstructorArguments.Length == 1 && attribute.ConstructorArguments.First().Value is int) { #nullable disable // Should use unboxed value from previous 'is int' https://github.com/dotnet/roslyn/issues/39166 var state = (EditorBrowsableState)attribute.ConstructorArguments.First().Value; #nullable enable if (EditorBrowsableState.Never == state) { return (isProhibited: true, isEditorBrowsableStateAdvanced: false); } if (EditorBrowsableState.Advanced == state) { return (isProhibited: hideAdvancedMembers, isEditorBrowsableStateAdvanced: true); } } } return (isProhibited: false, isEditorBrowsableStateAdvanced: false); } private static bool IsBrowsingProhibitedByTypeLibTypeAttribute( ImmutableArray<AttributeData> attributes, ImmutableArray<IMethodSymbol> constructors) { return IsBrowsingProhibitedByTypeLibAttributeWorker( attributes, constructors, TypeLibTypeFlagsFHidden); } private static bool IsBrowsingProhibitedByTypeLibFuncAttribute( ImmutableArray<AttributeData> attributes, ImmutableArray<IMethodSymbol> constructors) { return IsBrowsingProhibitedByTypeLibAttributeWorker( attributes, constructors, TypeLibFuncFlagsFHidden); } private static bool IsBrowsingProhibitedByTypeLibVarAttribute( ImmutableArray<AttributeData> attributes, ImmutableArray<IMethodSymbol> constructors) { return IsBrowsingProhibitedByTypeLibAttributeWorker( attributes, constructors, TypeLibVarFlagsFHidden); } private const int TypeLibTypeFlagsFHidden = 0x0010; private const int TypeLibFuncFlagsFHidden = 0x0040; private const int TypeLibVarFlagsFHidden = 0x0040; private static bool IsBrowsingProhibitedByTypeLibAttributeWorker( ImmutableArray<AttributeData> attributes, ImmutableArray<IMethodSymbol> attributeConstructors, int hiddenFlag) { foreach (var attribute in attributes) { if (attribute.ConstructorArguments.Length == 1) { foreach (var constructor in attributeConstructors) { if (Equals(attribute.AttributeConstructor, constructor)) { // Check for both constructor signatures. The constructor that takes a TypeLib*Flags reports an int argument. var argumentValue = attribute.ConstructorArguments.First().Value; int actualFlags; if (argumentValue is int i) { actualFlags = i; } else if (argumentValue is short sh) { actualFlags = sh; } else { continue; } if ((actualFlags & hiddenFlag) == hiddenFlag) { return true; } } } } } return false; } public static DocumentationComment GetDocumentationComment(this ISymbol symbol, Compilation compilation, CultureInfo? preferredCulture = null, bool expandIncludes = false, bool expandInheritdoc = false, CancellationToken cancellationToken = default) => GetDocumentationComment(symbol, visitedSymbols: null, compilation, preferredCulture, expandIncludes, expandInheritdoc, cancellationToken); private static DocumentationComment GetDocumentationComment(ISymbol symbol, HashSet<ISymbol>? visitedSymbols, Compilation compilation, CultureInfo? preferredCulture, bool expandIncludes, bool expandInheritdoc, CancellationToken cancellationToken) { var xmlText = symbol.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); if (expandInheritdoc) { if (string.IsNullOrEmpty(xmlText)) { if (IsEligibleForAutomaticInheritdoc(symbol)) { xmlText = $@"<doc><inheritdoc/></doc>"; } else { return DocumentationComment.Empty; } } try { var element = XElement.Parse(xmlText, LoadOptions.PreserveWhitespace); element.ReplaceNodes(RewriteMany(symbol, visitedSymbols, compilation, element.Nodes().ToArray(), cancellationToken)); xmlText = element.ToString(SaveOptions.DisableFormatting); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { } } return RoslynString.IsNullOrEmpty(xmlText) ? DocumentationComment.Empty : DocumentationComment.FromXmlFragment(xmlText); static bool IsEligibleForAutomaticInheritdoc(ISymbol symbol) { // Only the following symbols are eligible to inherit documentation without an <inheritdoc/> element: // // * Members that override an inherited member // * Members that implement an interface member if (symbol.IsOverride) { return true; } if (symbol.ContainingType is null) { // Observed with certain implicit operators, such as operator==(void*, void*). return false; } switch (symbol.Kind) { case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.Event: if (symbol.ExplicitOrImplicitInterfaceImplementations().Any()) { return true; } break; default: break; } return false; } } private static XNode[] RewriteInheritdocElements(ISymbol symbol, HashSet<ISymbol>? visitedSymbols, Compilation compilation, XNode node, CancellationToken cancellationToken) { if (node.NodeType == XmlNodeType.Element) { var element = (XElement)node; if (ElementNameIs(element, DocumentationCommentXmlNames.InheritdocElementName)) { var rewritten = RewriteInheritdocElement(symbol, visitedSymbols, compilation, element, cancellationToken); if (rewritten is object) { return rewritten; } } } var container = node as XContainer; if (container == null) { return new XNode[] { Copy(node, copyAttributeAnnotations: false) }; } var oldNodes = container.Nodes(); // Do this after grabbing the nodes, so we don't see copies of them. container = Copy(container, copyAttributeAnnotations: false); // WARN: don't use node after this point - use container since it's already been copied. if (oldNodes != null) { var rewritten = RewriteMany(symbol, visitedSymbols, compilation, oldNodes.ToArray(), cancellationToken); container.ReplaceNodes(rewritten); } return new XNode[] { container }; } private static XNode[] RewriteMany(ISymbol symbol, HashSet<ISymbol>? visitedSymbols, Compilation compilation, XNode[] nodes, CancellationToken cancellationToken) { var result = new List<XNode>(); foreach (var child in nodes) { result.AddRange(RewriteInheritdocElements(symbol, visitedSymbols, compilation, child, cancellationToken)); } return result.ToArray(); } private static XNode[]? RewriteInheritdocElement(ISymbol memberSymbol, HashSet<ISymbol>? visitedSymbols, Compilation compilation, XElement element, CancellationToken cancellationToken) { var crefAttribute = element.Attribute(XName.Get(DocumentationCommentXmlNames.CrefAttributeName)); var pathAttribute = element.Attribute(XName.Get(DocumentationCommentXmlNames.PathAttributeName)); var candidate = GetCandidateSymbol(memberSymbol); var hasCandidateCref = candidate is object; var hasCrefAttribute = crefAttribute is object; var hasPathAttribute = pathAttribute is object; if (!hasCrefAttribute && !hasCandidateCref) { // No cref available return null; } ISymbol? symbol; if (crefAttribute is null) { Contract.ThrowIfNull(candidate); symbol = candidate; } else { var crefValue = crefAttribute.Value; symbol = DocumentationCommentId.GetFirstSymbolForDeclarationId(crefValue, compilation); if (symbol is null) { return null; } } visitedSymbols ??= new HashSet<ISymbol>(); if (!visitedSymbols.Add(symbol)) { // Prevent recursion return null; } try { var inheritedDocumentation = GetDocumentationComment(symbol, visitedSymbols, compilation, preferredCulture: null, expandIncludes: true, expandInheritdoc: true, cancellationToken); if (inheritedDocumentation == DocumentationComment.Empty) { return Array.Empty<XNode>(); } var document = XDocument.Parse(inheritedDocumentation.FullXmlFragment); string xpathValue; if (string.IsNullOrEmpty(pathAttribute?.Value)) { xpathValue = BuildXPathForElement(element.Parent!); } else { xpathValue = pathAttribute!.Value; if (xpathValue.StartsWith("/")) { // Account for the root <doc> or <member> element xpathValue = "/*" + xpathValue; } } // Consider the following code, we want Test<int>.Clone to say "Clones a Test<int>" instead of "Clones a int", thus // we rewrite `typeparamref`s as cref pointing to the correct type: /* public class Test<T> : ICloneable<Test<T>> { /// <inheritdoc/> public Test<T> Clone() => new(); } /// <summary>A type that has clonable instances.</summary> /// <typeparam name="T">The type of instances that can be cloned.</typeparam> public interface ICloneable<T> { /// <summary>Clones a <typeparamref name="T"/>.</summary> public T Clone(); } */ // Note: there is no way to cref an instantiated generic type. See https://github.com/dotnet/csharplang/issues/401 var typeParameterRefs = document.Descendants(DocumentationCommentXmlNames.TypeParameterReferenceElementName).ToImmutableArray(); foreach (var typeParameterRef in typeParameterRefs) { if (typeParameterRef.Attribute(DocumentationCommentXmlNames.NameAttributeName) is var typeParamName) { var index = symbol.OriginalDefinition.GetAllTypeParameters().IndexOf(p => p.Name == typeParamName.Value); if (index >= 0) { var typeArgs = symbol.GetAllTypeArguments(); if (index < typeArgs.Length) { var docId = typeArgs[index].GetDocumentationCommentId(); var replacement = new XElement(DocumentationCommentXmlNames.SeeElementName); replacement.SetAttributeValue(DocumentationCommentXmlNames.CrefAttributeName, docId); typeParameterRef.ReplaceWith(replacement); } } } } var loadedElements = TrySelectNodes(document, xpathValue); return loadedElements ?? Array.Empty<XNode>(); } catch (XmlException) { return Array.Empty<XNode>(); } finally { visitedSymbols.Remove(symbol); } // Local functions static ISymbol? GetCandidateSymbol(ISymbol memberSymbol) { if (memberSymbol.ExplicitInterfaceImplementations().Any()) { return memberSymbol.ExplicitInterfaceImplementations().First(); } else if (memberSymbol.IsOverride) { return memberSymbol.GetOverriddenMember(); } if (memberSymbol is IMethodSymbol methodSymbol) { if (methodSymbol.MethodKind == MethodKind.Constructor || methodSymbol.MethodKind == MethodKind.StaticConstructor) { var baseType = memberSymbol.ContainingType.BaseType; #nullable disable // Can 'baseType' be null here? https://github.com/dotnet/roslyn/issues/39166 return baseType.Constructors.Where(c => IsSameSignature(methodSymbol, c)).FirstOrDefault(); #nullable enable } else { // check for implicit interface return methodSymbol.ExplicitOrImplicitInterfaceImplementations().FirstOrDefault(); } } else if (memberSymbol is INamedTypeSymbol typeSymbol) { if (typeSymbol.TypeKind == TypeKind.Class) { // Classes use the base type as the default inheritance candidate. A different target (e.g. an // interface) can be provided via the 'path' attribute. return typeSymbol.BaseType; } else if (typeSymbol.TypeKind == TypeKind.Interface) { return typeSymbol.Interfaces.FirstOrDefault(); } else { // This includes structs, enums, and delegates as mentioned in the inheritdoc spec return null; } } return memberSymbol.ExplicitOrImplicitInterfaceImplementations().FirstOrDefault(); } static bool IsSameSignature(IMethodSymbol left, IMethodSymbol right) { if (left.Parameters.Length != right.Parameters.Length) { return false; } if (left.IsStatic != right.IsStatic) { return false; } if (!left.ReturnType.Equals(right.ReturnType)) { return false; } for (var i = 0; i < left.Parameters.Length; i++) { if (!left.Parameters[i].Type.Equals(right.Parameters[i].Type)) { return false; } } return true; } static string BuildXPathForElement(XElement element) { if (ElementNameIs(element, "member") || ElementNameIs(element, "doc")) { // Avoid string concatenation allocations for inheritdoc as a top-level element return "/*/node()[not(self::overloads)]"; } var path = "/node()[not(self::overloads)]"; for (var current = element; current != null; current = current.Parent) { var currentName = current.Name.ToString(); if (ElementNameIs(current, "member") || ElementNameIs(current, "doc")) { // Allow <member> and <doc> to be used interchangeably currentName = "*"; } path = "/" + currentName + path; } return path; } } private static TNode Copy<TNode>(TNode node, bool copyAttributeAnnotations) where TNode : XNode { XNode copy; // Documents can't be added to containers, so our usual copy trick won't work. if (node.NodeType == XmlNodeType.Document) { copy = new XDocument(((XDocument)(object)node)); } else { XContainer temp = new XElement("temp"); temp.Add(node); copy = temp.LastNode!; temp.RemoveNodes(); } Debug.Assert(copy != node); Debug.Assert(copy.Parent == null); // Otherwise, when we give it one, it will be copied. // Copy annotations, the above doesn't preserve them. // We need to preserve Location annotations as well as line position annotations. CopyAnnotations(node, copy); // We also need to preserve line position annotations for all attributes // since we report errors with attribute locations. if (copyAttributeAnnotations && node.NodeType == XmlNodeType.Element) { var sourceElement = (XElement)(object)node; var targetElement = (XElement)copy; var sourceAttributes = sourceElement.Attributes().GetEnumerator(); var targetAttributes = targetElement.Attributes().GetEnumerator(); while (sourceAttributes.MoveNext() && targetAttributes.MoveNext()) { Debug.Assert(sourceAttributes.Current.Name == targetAttributes.Current.Name); CopyAnnotations(sourceAttributes.Current, targetAttributes.Current); } } return (TNode)copy; } private static void CopyAnnotations(XObject source, XObject target) { foreach (var annotation in source.Annotations<object>()) { target.AddAnnotation(annotation); } } private static XNode[]? TrySelectNodes(XNode node, string xpath) { try { var xpathResult = (IEnumerable)System.Xml.XPath.Extensions.XPathEvaluate(node, xpath); // Throws InvalidOperationException if the result of the XPath is an XDocument: return xpathResult?.Cast<XNode>().ToArray(); } catch (InvalidOperationException) { return null; } catch (XPathException) { return null; } } private static bool ElementNameIs(XElement element, string name) => string.IsNullOrEmpty(element.Name.NamespaceName) && DocumentationCommentXmlNames.ElementEquals(element.Name.LocalName, name); /// <summary> /// First, remove symbols from the set if they are overridden by other symbols in the set. /// If a symbol is overridden only by symbols outside of the set, then it is not removed. /// This is useful for filtering out symbols that cannot be accessed in a given context due /// to the existence of overriding members. Second, remove remaining symbols that are /// unsupported (e.g. pointer types in VB) or not editor browsable based on the EditorBrowsable /// attribute. /// </summary> public static ImmutableArray<T> FilterToVisibleAndBrowsableSymbols<T>( this ImmutableArray<T> symbols, bool hideAdvancedMembers, Compilation compilation) where T : ISymbol { symbols = symbols.RemoveOverriddenSymbolsWithinSet(); // Since all symbols are from the same compilation, find the required attribute // constructors once and reuse. var editorBrowsableInfo = new EditorBrowsableInfo(compilation); // PERF: HasUnsupportedMetadata may require recreating the syntax tree to get the base class, so first // check to see if we're referencing a symbol defined in source. static bool isSymbolDefinedInSource(Location l) => l.IsInSource; return symbols.WhereAsArray((s, arg) => (s.Locations.Any(isSymbolDefinedInSource) || !s.HasUnsupportedMetadata) && !s.IsDestructor() && s.IsEditorBrowsable( arg.hideAdvancedMembers, arg.editorBrowsableInfo.Compilation, arg.editorBrowsableInfo), (hideAdvancedMembers, editorBrowsableInfo)); } private static ImmutableArray<T> RemoveOverriddenSymbolsWithinSet<T>(this ImmutableArray<T> symbols) where T : ISymbol { var overriddenSymbols = new HashSet<ISymbol>(); foreach (var symbol in symbols) { var overriddenMember = symbol.GetOverriddenMember(); if (overriddenMember != null && !overriddenSymbols.Contains(overriddenMember)) overriddenSymbols.Add(overriddenMember); } return symbols.WhereAsArray(s => !overriddenSymbols.Contains(s)); } public static ImmutableArray<T> FilterToVisibleAndBrowsableSymbolsAndNotUnsafeSymbols<T>( this ImmutableArray<T> symbols, bool hideAdvancedMembers, Compilation compilation) where T : ISymbol { return symbols.FilterToVisibleAndBrowsableSymbols(hideAdvancedMembers, compilation) .WhereAsArray(s => !s.RequiresUnsafeModifier()); } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Test/WinRT/WinRTUtil.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.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { internal static class WinRTUtil { internal static CompilationVerifier CompileAndVerifyOnWin8Only( this CSharpTestBase testBase, string source, MetadataReference[] additionalRefs = null, string expectedOutput = null) { var isWin8 = OSVersion.IsWin8; return testBase.CompileAndVerifyWithWinRt( source, references: additionalRefs, expectedOutput: isWin8 ? expectedOutput : null, verify: isWin8 ? Verification.Passes : Verification.Fails); } } }
// Licensed to the .NET Foundation under one or more 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.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { internal static class WinRTUtil { internal static CompilationVerifier CompileAndVerifyOnWin8Only( this CSharpTestBase testBase, string source, MetadataReference[] additionalRefs = null, string expectedOutput = null) { var isWin8 = OSVersion.IsWin8; return testBase.CompileAndVerifyWithWinRt( source, references: additionalRefs, expectedOutput: isWin8 ? expectedOutput : null, verify: isWin8 ? Verification.Passes : Verification.Fails); } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/AddConstructorParametersFromMembers/AddConstructorParametersFromMembersCodeRefactoringProvider.ConstructorCandidate.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.AddConstructorParametersFromMembers { internal partial class AddConstructorParametersFromMembersCodeRefactoringProvider { private readonly struct ConstructorCandidate { public readonly IMethodSymbol Constructor; public readonly ImmutableArray<ISymbol> MissingMembers; public readonly ImmutableArray<IParameterSymbol> MissingParameters; public ConstructorCandidate(IMethodSymbol constructor, ImmutableArray<ISymbol> missingMembers, ImmutableArray<IParameterSymbol> missingParameters) { Constructor = constructor; MissingMembers = missingMembers; MissingParameters = missingParameters; } } } }
// Licensed to the .NET Foundation under one or more 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.AddConstructorParametersFromMembers { internal partial class AddConstructorParametersFromMembersCodeRefactoringProvider { private readonly struct ConstructorCandidate { public readonly IMethodSymbol Constructor; public readonly ImmutableArray<ISymbol> MissingMembers; public readonly ImmutableArray<IParameterSymbol> MissingParameters; public ConstructorCandidate(IMethodSymbol constructor, ImmutableArray<ISymbol> missingMembers, ImmutableArray<IParameterSymbol> missingParameters) { Constructor = constructor; MissingMembers = missingMembers; MissingParameters = missingParameters; } } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Tools/AnalyzerRunner/PersistentStorageLocationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.IO; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace AnalyzerRunner { [ExportWorkspaceService(typeof(IPersistentStorageLocationService), ServiceLayer.Host)] [Shared] internal class PersistentStorageLocationService : IPersistentStorageLocationService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PersistentStorageLocationService() { } public bool IsSupported(Workspace workspace) => true; public string TryGetStorageLocation(Solution _) { var location = Path.Combine(Path.GetTempPath(), "RoslynTests", "AnalyzerRunner", "temp-db"); Directory.CreateDirectory(location); return location; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.IO; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace AnalyzerRunner { [ExportWorkspaceService(typeof(IPersistentStorageLocationService), ServiceLayer.Host)] [Shared] internal class PersistentStorageLocationService : IPersistentStorageLocationService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PersistentStorageLocationService() { } public bool IsSupported(Workspace workspace) => true; public string TryGetStorageLocation(Solution _) { var location = Path.Combine(Path.GetTempPath(), "RoslynTests", "AnalyzerRunner", "temp-db"); Directory.CreateDirectory(location); return location; } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Def/Implementation/Progression/GraphQueries/SearchGraphQuery.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.Linq; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.NavigateTo; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.GraphModel; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal sealed partial class SearchGraphQuery : IGraphQuery { private readonly IThreadingContext _threadingContext; private readonly IAsynchronousOperationListener _asyncListener; private readonly string _searchPattern; public SearchGraphQuery( string searchPattern, IThreadingContext threadingContext, IAsynchronousOperationListener asyncListener) { _threadingContext = threadingContext; _asyncListener = asyncListener; _searchPattern = searchPattern; } public Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { var experimentationService = solution.Workspace.Services.GetService<IExperimentationService>(); var forceLegacySearch = experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.ProgressionForceLegacySearch) == true; var option = solution.Options.GetOption(ProgressionOptions.SearchUsingNavigateToEngine); return !forceLegacySearch && option ? SearchUsingNavigateToEngineAsync(solution, context, cancellationToken) : SearchUsingSymbolsAsync(solution, context, cancellationToken); } private async Task<GraphBuilder> SearchUsingNavigateToEngineAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); var callback = new ProgressionNavigateToSearchCallback(context, graphBuilder); var searcher = NavigateToSearcher.Create( solution, _asyncListener, callback, _searchPattern, searchCurrentDocument: false, NavigateToUtilities.GetKindsProvided(solution), _threadingContext.DisposalToken); await searcher.SearchAsync(cancellationToken).ConfigureAwait(false); return graphBuilder; } private async Task<GraphBuilder> SearchUsingSymbolsAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); var searchTasks = solution.Projects .Where(p => p.FilePath != null) .Select(p => ProcessProjectAsync(p, graphBuilder, cancellationToken)) .ToArray(); await Task.WhenAll(searchTasks).ConfigureAwait(false); return graphBuilder; } private async Task ProcessProjectAsync(Project project, GraphBuilder graphBuilder, CancellationToken cancellationToken) { var cacheService = project.Solution.Services.CacheService; if (cacheService != null) { using (cacheService.EnableCaching(project.Id)) { var results = await FindNavigableSourceSymbolsAsync(project, cancellationToken).ConfigureAwait(false); foreach (var symbol in results) { cancellationToken.ThrowIfCancellationRequested(); if (symbol is INamedTypeSymbol namedType) { await AddLinkedNodeForTypeAsync( project, namedType, graphBuilder, symbol.DeclaringSyntaxReferences.Select(d => d.SyntaxTree), cancellationToken).ConfigureAwait(false); } else { await AddLinkedNodeForMemberAsync( project, symbol, graphBuilder, cancellationToken).ConfigureAwait(false); } } } } } private async Task<GraphNode> AddLinkedNodeForTypeAsync( Project project, INamedTypeSymbol namedType, GraphBuilder graphBuilder, IEnumerable<SyntaxTree> syntaxTrees, CancellationToken cancellationToken) { // If this named type is contained in a parent type, then just link farther up if (namedType.ContainingType != null) { var parentTypeNode = await AddLinkedNodeForTypeAsync( project, namedType.ContainingType, graphBuilder, syntaxTrees, cancellationToken).ConfigureAwait(false); var typeNode = await graphBuilder.AddNodeAsync(namedType, relatedNode: parentTypeNode, cancellationToken).ConfigureAwait(false); graphBuilder.AddLink(parentTypeNode, GraphCommonSchema.Contains, typeNode, cancellationToken); return typeNode; } else { // From here, we can link back up to the containing project item var typeNode = await graphBuilder.AddNodeAsync( namedType, contextProject: project, contextDocument: null, cancellationToken).ConfigureAwait(false); foreach (var tree in syntaxTrees) { var document = project.Solution.GetDocument(tree); Contract.ThrowIfNull(document); var documentNode = graphBuilder.AddNodeForDocument(document, cancellationToken); graphBuilder.AddLink(documentNode, GraphCommonSchema.Contains, typeNode, cancellationToken); } return typeNode; } } private async Task<GraphNode> AddLinkedNodeForMemberAsync( Project project, ISymbol symbol, GraphBuilder graphBuilder, CancellationToken cancellationToken) { var member = symbol; Contract.ThrowIfNull(member.ContainingType); var trees = member.DeclaringSyntaxReferences.Select(d => d.SyntaxTree); var parentTypeNode = await AddLinkedNodeForTypeAsync( project, member.ContainingType, graphBuilder, trees, cancellationToken).ConfigureAwait(false); var memberNode = await graphBuilder.AddNodeAsync( symbol, relatedNode: parentTypeNode, cancellationToken).ConfigureAwait(false); graphBuilder.AddLink(parentTypeNode, GraphCommonSchema.Contains, memberNode, cancellationToken); return memberNode; } internal async Task<ImmutableArray<ISymbol>> FindNavigableSourceSymbolsAsync( Project project, CancellationToken cancellationToken) { ImmutableArray<ISymbol> declarations; // FindSourceDeclarationsWithPatternAsync calls into OOP to do the search; if something goes badly it // throws a SoftCrashException which inherits from OperationCanceledException. This is unfortunate, because // it means that other bits of code see this as a cancellation and then may crash because they expect that if this // method is raising cancellation, it's because cancellationToken requested the cancellation. The intent behind // SoftCrashException was since it inherited from OperationCancelled it would make things safer, but in this case // it's violating other invariants in the process which creates other problems. // // https://github.com/dotnet/roslyn/issues/40476 tracks removing SoftCrashException. When it is removed, the // catch here can be removed and simply let the exception propagate; our Progression code is hardened to // handle exceptions and report them gracefully. try { declarations = await DeclarationFinder.FindSourceDeclarationsWithPatternAsync( project, _searchPattern, SymbolFilter.TypeAndMember, cancellationToken).ConfigureAwait(false); } catch (SoftCrashException ex) when (ex.InnerException != null) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); throw ExceptionUtilities.Unreachable; } using var _ = ArrayBuilder<ISymbol>.GetInstance(out var results); foreach (var declaration in declarations) { cancellationToken.ThrowIfCancellationRequested(); var symbol = declaration; // Ignore constructors and namespaces. We don't want to expose them through this API. if (symbol.IsConstructor() || symbol.IsStaticConstructor() || symbol is INamespaceSymbol) { continue; } // Ignore symbols that have no source location. We don't want to expose them through this API. if (!symbol.Locations.Any(loc => loc.IsInSource)) { continue; } results.Add(declaration); // also report matching constructors (using same match result as type) if (symbol is INamedTypeSymbol namedType) { foreach (var constructor in namedType.Constructors) { // only constructors that were explicitly declared if (!constructor.IsImplicitlyDeclared) { results.Add(constructor); } } } // report both parts of partial methods if (symbol is IMethodSymbol method && method.PartialImplementationPart != null) { results.Add(method); } } return results.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.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.NavigateTo; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.GraphModel; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal sealed partial class SearchGraphQuery : IGraphQuery { private readonly IThreadingContext _threadingContext; private readonly IAsynchronousOperationListener _asyncListener; private readonly string _searchPattern; public SearchGraphQuery( string searchPattern, IThreadingContext threadingContext, IAsynchronousOperationListener asyncListener) { _threadingContext = threadingContext; _asyncListener = asyncListener; _searchPattern = searchPattern; } public Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { var experimentationService = solution.Workspace.Services.GetService<IExperimentationService>(); var forceLegacySearch = experimentationService?.IsExperimentEnabled(WellKnownExperimentNames.ProgressionForceLegacySearch) == true; var option = solution.Options.GetOption(ProgressionOptions.SearchUsingNavigateToEngine); return !forceLegacySearch && option ? SearchUsingNavigateToEngineAsync(solution, context, cancellationToken) : SearchUsingSymbolsAsync(solution, context, cancellationToken); } private async Task<GraphBuilder> SearchUsingNavigateToEngineAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); var callback = new ProgressionNavigateToSearchCallback(context, graphBuilder); var searcher = NavigateToSearcher.Create( solution, _asyncListener, callback, _searchPattern, searchCurrentDocument: false, NavigateToUtilities.GetKindsProvided(solution), _threadingContext.DisposalToken); await searcher.SearchAsync(cancellationToken).ConfigureAwait(false); return graphBuilder; } private async Task<GraphBuilder> SearchUsingSymbolsAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); var searchTasks = solution.Projects .Where(p => p.FilePath != null) .Select(p => ProcessProjectAsync(p, graphBuilder, cancellationToken)) .ToArray(); await Task.WhenAll(searchTasks).ConfigureAwait(false); return graphBuilder; } private async Task ProcessProjectAsync(Project project, GraphBuilder graphBuilder, CancellationToken cancellationToken) { var cacheService = project.Solution.Services.CacheService; if (cacheService != null) { using (cacheService.EnableCaching(project.Id)) { var results = await FindNavigableSourceSymbolsAsync(project, cancellationToken).ConfigureAwait(false); foreach (var symbol in results) { cancellationToken.ThrowIfCancellationRequested(); if (symbol is INamedTypeSymbol namedType) { await AddLinkedNodeForTypeAsync( project, namedType, graphBuilder, symbol.DeclaringSyntaxReferences.Select(d => d.SyntaxTree), cancellationToken).ConfigureAwait(false); } else { await AddLinkedNodeForMemberAsync( project, symbol, graphBuilder, cancellationToken).ConfigureAwait(false); } } } } } private async Task<GraphNode> AddLinkedNodeForTypeAsync( Project project, INamedTypeSymbol namedType, GraphBuilder graphBuilder, IEnumerable<SyntaxTree> syntaxTrees, CancellationToken cancellationToken) { // If this named type is contained in a parent type, then just link farther up if (namedType.ContainingType != null) { var parentTypeNode = await AddLinkedNodeForTypeAsync( project, namedType.ContainingType, graphBuilder, syntaxTrees, cancellationToken).ConfigureAwait(false); var typeNode = await graphBuilder.AddNodeAsync(namedType, relatedNode: parentTypeNode, cancellationToken).ConfigureAwait(false); graphBuilder.AddLink(parentTypeNode, GraphCommonSchema.Contains, typeNode, cancellationToken); return typeNode; } else { // From here, we can link back up to the containing project item var typeNode = await graphBuilder.AddNodeAsync( namedType, contextProject: project, contextDocument: null, cancellationToken).ConfigureAwait(false); foreach (var tree in syntaxTrees) { var document = project.Solution.GetDocument(tree); Contract.ThrowIfNull(document); var documentNode = graphBuilder.AddNodeForDocument(document, cancellationToken); graphBuilder.AddLink(documentNode, GraphCommonSchema.Contains, typeNode, cancellationToken); } return typeNode; } } private async Task<GraphNode> AddLinkedNodeForMemberAsync( Project project, ISymbol symbol, GraphBuilder graphBuilder, CancellationToken cancellationToken) { var member = symbol; Contract.ThrowIfNull(member.ContainingType); var trees = member.DeclaringSyntaxReferences.Select(d => d.SyntaxTree); var parentTypeNode = await AddLinkedNodeForTypeAsync( project, member.ContainingType, graphBuilder, trees, cancellationToken).ConfigureAwait(false); var memberNode = await graphBuilder.AddNodeAsync( symbol, relatedNode: parentTypeNode, cancellationToken).ConfigureAwait(false); graphBuilder.AddLink(parentTypeNode, GraphCommonSchema.Contains, memberNode, cancellationToken); return memberNode; } internal async Task<ImmutableArray<ISymbol>> FindNavigableSourceSymbolsAsync( Project project, CancellationToken cancellationToken) { ImmutableArray<ISymbol> declarations; // FindSourceDeclarationsWithPatternAsync calls into OOP to do the search; if something goes badly it // throws a SoftCrashException which inherits from OperationCanceledException. This is unfortunate, because // it means that other bits of code see this as a cancellation and then may crash because they expect that if this // method is raising cancellation, it's because cancellationToken requested the cancellation. The intent behind // SoftCrashException was since it inherited from OperationCancelled it would make things safer, but in this case // it's violating other invariants in the process which creates other problems. // // https://github.com/dotnet/roslyn/issues/40476 tracks removing SoftCrashException. When it is removed, the // catch here can be removed and simply let the exception propagate; our Progression code is hardened to // handle exceptions and report them gracefully. try { declarations = await DeclarationFinder.FindSourceDeclarationsWithPatternAsync( project, _searchPattern, SymbolFilter.TypeAndMember, cancellationToken).ConfigureAwait(false); } catch (SoftCrashException ex) when (ex.InnerException != null) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); throw ExceptionUtilities.Unreachable; } using var _ = ArrayBuilder<ISymbol>.GetInstance(out var results); foreach (var declaration in declarations) { cancellationToken.ThrowIfCancellationRequested(); var symbol = declaration; // Ignore constructors and namespaces. We don't want to expose them through this API. if (symbol.IsConstructor() || symbol.IsStaticConstructor() || symbol is INamespaceSymbol) { continue; } // Ignore symbols that have no source location. We don't want to expose them through this API. if (!symbol.Locations.Any(loc => loc.IsInSource)) { continue; } results.Add(declaration); // also report matching constructors (using same match result as type) if (symbol is INamedTypeSymbol namedType) { foreach (var constructor in namedType.Constructors) { // only constructors that were explicitly declared if (!constructor.IsImplicitlyDeclared) { results.Add(constructor); } } } // report both parts of partial methods if (symbol is IMethodSymbol method && method.PartialImplementationPart != null) { results.Add(method); } } return results.ToImmutable(); } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpExtractInterfaceDialog.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; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpExtractInterfaceDialog : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; private ExtractInterfaceDialog_OutOfProc ExtractInterfaceDialog => VisualStudio.ExtractInterfaceDialog; public CSharpExtractInterfaceDialog(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpExtractInterfaceDialog)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void VerifyCancellation() { SetUpEditor(@"class C$$ { public void M() { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); ExtractInterfaceDialog.ClickCancel(); ExtractInterfaceDialog.VerifyClosed(); VisualStudio.Editor.Verify.TextContains(@"class C { public void M() { } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void CheckFileName() { SetUpEditor(@"class C$$ { public void M() { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); var targetFileName = ExtractInterfaceDialog.GetTargetFileName(); Assert.Equal(expected: "IC.cs", actual: targetFileName); ExtractInterfaceDialog.ClickCancel(); ExtractInterfaceDialog.VerifyClosed(); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void VerifySelectAndDeselectAllButtons() { SetUpEditor(@"class C$$ { public void M1() { } public void M2() { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); var selectedItems = ExtractInterfaceDialog.GetSelectedItems(); Assert.Equal( expected: new[] { "M1()", "M2()" }, actual: selectedItems); ExtractInterfaceDialog.ClickDeselectAll(); selectedItems = ExtractInterfaceDialog.GetSelectedItems(); Assert.Empty(selectedItems); ExtractInterfaceDialog.ClickSelectAll(); selectedItems = ExtractInterfaceDialog.GetSelectedItems(); Assert.Equal( expected: new[] { "M1()", "M2()" }, actual: selectedItems); ExtractInterfaceDialog.ClickCancel(); ExtractInterfaceDialog.VerifyClosed(); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void OnlySelectedItemsAreGenerated() { SetUpEditor(@"class C$$ { public void M1() { } public void M2() { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); ExtractInterfaceDialog.ClickDeselectAll(); ExtractInterfaceDialog.ToggleItem("M2()"); ExtractInterfaceDialog.ClickOK(); ExtractInterfaceDialog.VerifyClosed(); var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.OpenFile(project, "Class1.cs"); VisualStudio.Editor.Verify.TextContains(@"class C : IC { public void M1() { } public void M2() { } } "); VisualStudio.SolutionExplorer.OpenFile(project, "IC.cs"); VisualStudio.Editor.Verify.TextContains(@"interface IC { void M2(); }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void CheckSameFile() { SetUpEditor(@"class C$$ { public void M() { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); ExtractInterfaceDialog.SelectSameFile(); ExtractInterfaceDialog.ClickOK(); ExtractInterfaceDialog.VerifyClosed(); _ = new ProjectUtils.Project(ProjectName); VisualStudio.Editor.Verify.TextContains(@"interface IC { void M(); } class C : IC { public void M() { } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void CheckSameFileOnlySelectedItems() { SetUpEditor(@"class C$$ { public void M1() { } public void M2() { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); ExtractInterfaceDialog.ClickDeselectAll(); ExtractInterfaceDialog.ToggleItem("M2()"); ExtractInterfaceDialog.SelectSameFile(); ExtractInterfaceDialog.ClickOK(); ExtractInterfaceDialog.VerifyClosed(); VisualStudio.Editor.Verify.TextContains(@"interface IC { void M2(); } class C : IC { public void M1() { } public void M2() { } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void CheckSameFileNamespace() { SetUpEditor(@"namespace A { class C$$ { public void M() { } } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); ExtractInterfaceDialog.SelectSameFile(); ExtractInterfaceDialog.ClickOK(); ExtractInterfaceDialog.VerifyClosed(); _ = new ProjectUtils.Project(ProjectName); VisualStudio.Editor.Verify.TextContains(@"namespace A { interface IC { void M(); } class C : IC { public void M() { } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void CheckSameWithTypes() { SetUpEditor(@"class C$$ { public bool M() => false; } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); ExtractInterfaceDialog.SelectSameFile(); ExtractInterfaceDialog.ClickOK(); ExtractInterfaceDialog.VerifyClosed(); _ = new ProjectUtils.Project(ProjectName); VisualStudio.Editor.Verify.TextContains(@"interface IC { bool M(); } class C : IC { public bool M() => 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 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; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpExtractInterfaceDialog : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; private ExtractInterfaceDialog_OutOfProc ExtractInterfaceDialog => VisualStudio.ExtractInterfaceDialog; public CSharpExtractInterfaceDialog(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpExtractInterfaceDialog)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void VerifyCancellation() { SetUpEditor(@"class C$$ { public void M() { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); ExtractInterfaceDialog.ClickCancel(); ExtractInterfaceDialog.VerifyClosed(); VisualStudio.Editor.Verify.TextContains(@"class C { public void M() { } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void CheckFileName() { SetUpEditor(@"class C$$ { public void M() { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); var targetFileName = ExtractInterfaceDialog.GetTargetFileName(); Assert.Equal(expected: "IC.cs", actual: targetFileName); ExtractInterfaceDialog.ClickCancel(); ExtractInterfaceDialog.VerifyClosed(); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void VerifySelectAndDeselectAllButtons() { SetUpEditor(@"class C$$ { public void M1() { } public void M2() { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); var selectedItems = ExtractInterfaceDialog.GetSelectedItems(); Assert.Equal( expected: new[] { "M1()", "M2()" }, actual: selectedItems); ExtractInterfaceDialog.ClickDeselectAll(); selectedItems = ExtractInterfaceDialog.GetSelectedItems(); Assert.Empty(selectedItems); ExtractInterfaceDialog.ClickSelectAll(); selectedItems = ExtractInterfaceDialog.GetSelectedItems(); Assert.Equal( expected: new[] { "M1()", "M2()" }, actual: selectedItems); ExtractInterfaceDialog.ClickCancel(); ExtractInterfaceDialog.VerifyClosed(); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void OnlySelectedItemsAreGenerated() { SetUpEditor(@"class C$$ { public void M1() { } public void M2() { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); ExtractInterfaceDialog.ClickDeselectAll(); ExtractInterfaceDialog.ToggleItem("M2()"); ExtractInterfaceDialog.ClickOK(); ExtractInterfaceDialog.VerifyClosed(); var project = new ProjectUtils.Project(ProjectName); VisualStudio.SolutionExplorer.OpenFile(project, "Class1.cs"); VisualStudio.Editor.Verify.TextContains(@"class C : IC { public void M1() { } public void M2() { } } "); VisualStudio.SolutionExplorer.OpenFile(project, "IC.cs"); VisualStudio.Editor.Verify.TextContains(@"interface IC { void M2(); }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void CheckSameFile() { SetUpEditor(@"class C$$ { public void M() { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); ExtractInterfaceDialog.SelectSameFile(); ExtractInterfaceDialog.ClickOK(); ExtractInterfaceDialog.VerifyClosed(); _ = new ProjectUtils.Project(ProjectName); VisualStudio.Editor.Verify.TextContains(@"interface IC { void M(); } class C : IC { public void M() { } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void CheckSameFileOnlySelectedItems() { SetUpEditor(@"class C$$ { public void M1() { } public void M2() { } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); ExtractInterfaceDialog.ClickDeselectAll(); ExtractInterfaceDialog.ToggleItem("M2()"); ExtractInterfaceDialog.SelectSameFile(); ExtractInterfaceDialog.ClickOK(); ExtractInterfaceDialog.VerifyClosed(); VisualStudio.Editor.Verify.TextContains(@"interface IC { void M2(); } class C : IC { public void M1() { } public void M2() { } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void CheckSameFileNamespace() { SetUpEditor(@"namespace A { class C$$ { public void M() { } } } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); ExtractInterfaceDialog.SelectSameFile(); ExtractInterfaceDialog.ClickOK(); ExtractInterfaceDialog.VerifyClosed(); _ = new ProjectUtils.Project(ProjectName); VisualStudio.Editor.Verify.TextContains(@"namespace A { interface IC { void M(); } class C : IC { public void M() { } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractInterface)] public void CheckSameWithTypes() { SetUpEditor(@"class C$$ { public bool M() => false; } "); VisualStudio.Editor.InvokeCodeActionList(); VisualStudio.Editor.Verify.CodeAction("Extract interface...", applyFix: true, blockUntilComplete: false); ExtractInterfaceDialog.VerifyOpen(); ExtractInterfaceDialog.SelectSameFile(); ExtractInterfaceDialog.ClickOK(); ExtractInterfaceDialog.VerifyClosed(); _ = new ProjectUtils.Project(ProjectName); VisualStudio.Editor.Verify.TextContains(@"interface IC { bool M(); } class C : IC { public bool M() => false; } "); } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/Compilation/RebuildData.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.Linq; using System.Reflection.Metadata; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { internal sealed class RebuildData { /// <summary> /// This represents the set of document names for the #line / #ExternalSource directives /// that we need to emit into the PDB (in the order specified in the array). /// </summary> internal ImmutableArray<string> NonSourceFileDocumentNames { get; } internal BlobReader OptionsBlobReader { get; } internal RebuildData( BlobReader optionsBlobReader, ImmutableArray<string> nonSourceFileDocumentNames) { OptionsBlobReader = optionsBlobReader; NonSourceFileDocumentNames = nonSourceFileDocumentNames; } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Reflection.Metadata; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { internal sealed class RebuildData { /// <summary> /// This represents the set of document names for the #line / #ExternalSource directives /// that we need to emit into the PDB (in the order specified in the array). /// </summary> internal ImmutableArray<string> NonSourceFileDocumentNames { get; } internal BlobReader OptionsBlobReader { get; } internal RebuildData( BlobReader optionsBlobReader, ImmutableArray<string> nonSourceFileDocumentNames) { OptionsBlobReader = optionsBlobReader; NonSourceFileDocumentNames = nonSourceFileDocumentNames; } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Impl/SolutionExplorer/DiagnosticItem/CpsDiagnosticItemSource.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel; using System.IO; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.Internal.VisualStudio.PlatformUI; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { internal partial class CpsDiagnosticItemSource : BaseDiagnosticAndGeneratorItemSource, INotifyPropertyChanged { private readonly IVsHierarchyItem _item; private readonly string _projectDirectoryPath; private AnalyzerReference? _analyzerReference; public event PropertyChangedEventHandler? PropertyChanged; public CpsDiagnosticItemSource(Workspace workspace, string projectPath, ProjectId projectId, IVsHierarchyItem item, IAnalyzersCommandHandler commandHandler, IDiagnosticAnalyzerService analyzerService) : base(workspace, projectId, commandHandler, analyzerService) { _item = item; _projectDirectoryPath = Path.GetDirectoryName(projectPath); _analyzerReference = TryGetAnalyzerReference(Workspace.CurrentSolution); if (_analyzerReference == null) { // The workspace doesn't know about the project and/or the analyzer yet. // Hook up an event handler so we can update when it does. Workspace.WorkspaceChanged += OnWorkspaceChangedLookForAnalyzer; } } public IContextMenuController DiagnosticItemContextMenuController => CommandHandler.DiagnosticContextMenuController; public override object SourceItem => _item; public override AnalyzerReference? AnalyzerReference => _analyzerReference; private void OnWorkspaceChangedLookForAnalyzer(object sender, WorkspaceChangeEventArgs e) { if (e.Kind == WorkspaceChangeKind.SolutionCleared || e.Kind == WorkspaceChangeKind.SolutionReloaded || e.Kind == WorkspaceChangeKind.SolutionRemoved) { Workspace.WorkspaceChanged -= OnWorkspaceChangedLookForAnalyzer; } else if (e.Kind == WorkspaceChangeKind.SolutionAdded) { _analyzerReference = TryGetAnalyzerReference(e.NewSolution); if (_analyzerReference != null) { Workspace.WorkspaceChanged -= OnWorkspaceChangedLookForAnalyzer; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(HasItems))); } } else if (e.ProjectId == ProjectId) { if (e.Kind == WorkspaceChangeKind.ProjectRemoved) { Workspace.WorkspaceChanged -= OnWorkspaceChangedLookForAnalyzer; } else if (e.Kind == WorkspaceChangeKind.ProjectAdded || e.Kind == WorkspaceChangeKind.ProjectChanged) { _analyzerReference = TryGetAnalyzerReference(e.NewSolution); if (_analyzerReference != null) { Workspace.WorkspaceChanged -= OnWorkspaceChangedLookForAnalyzer; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(HasItems))); } } } } private AnalyzerReference? TryGetAnalyzerReference(Solution solution) { var project = solution.GetProject(ProjectId); if (project == null) { return null; } var canonicalName = _item.CanonicalName; var analyzerFilePath = CpsUtilities.ExtractAnalyzerFilePath(_projectDirectoryPath, canonicalName); if (string.IsNullOrEmpty(analyzerFilePath)) { return null; } return project.AnalyzerReferences.FirstOrDefault(r => string.Equals(r.FullPath, analyzerFilePath, StringComparison.OrdinalIgnoreCase)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel; using System.IO; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.Internal.VisualStudio.PlatformUI; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { internal partial class CpsDiagnosticItemSource : BaseDiagnosticAndGeneratorItemSource, INotifyPropertyChanged { private readonly IVsHierarchyItem _item; private readonly string _projectDirectoryPath; private AnalyzerReference? _analyzerReference; public event PropertyChangedEventHandler? PropertyChanged; public CpsDiagnosticItemSource(Workspace workspace, string projectPath, ProjectId projectId, IVsHierarchyItem item, IAnalyzersCommandHandler commandHandler, IDiagnosticAnalyzerService analyzerService) : base(workspace, projectId, commandHandler, analyzerService) { _item = item; _projectDirectoryPath = Path.GetDirectoryName(projectPath); _analyzerReference = TryGetAnalyzerReference(Workspace.CurrentSolution); if (_analyzerReference == null) { // The workspace doesn't know about the project and/or the analyzer yet. // Hook up an event handler so we can update when it does. Workspace.WorkspaceChanged += OnWorkspaceChangedLookForAnalyzer; } } public IContextMenuController DiagnosticItemContextMenuController => CommandHandler.DiagnosticContextMenuController; public override object SourceItem => _item; public override AnalyzerReference? AnalyzerReference => _analyzerReference; private void OnWorkspaceChangedLookForAnalyzer(object sender, WorkspaceChangeEventArgs e) { if (e.Kind == WorkspaceChangeKind.SolutionCleared || e.Kind == WorkspaceChangeKind.SolutionReloaded || e.Kind == WorkspaceChangeKind.SolutionRemoved) { Workspace.WorkspaceChanged -= OnWorkspaceChangedLookForAnalyzer; } else if (e.Kind == WorkspaceChangeKind.SolutionAdded) { _analyzerReference = TryGetAnalyzerReference(e.NewSolution); if (_analyzerReference != null) { Workspace.WorkspaceChanged -= OnWorkspaceChangedLookForAnalyzer; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(HasItems))); } } else if (e.ProjectId == ProjectId) { if (e.Kind == WorkspaceChangeKind.ProjectRemoved) { Workspace.WorkspaceChanged -= OnWorkspaceChangedLookForAnalyzer; } else if (e.Kind == WorkspaceChangeKind.ProjectAdded || e.Kind == WorkspaceChangeKind.ProjectChanged) { _analyzerReference = TryGetAnalyzerReference(e.NewSolution); if (_analyzerReference != null) { Workspace.WorkspaceChanged -= OnWorkspaceChangedLookForAnalyzer; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(HasItems))); } } } } private AnalyzerReference? TryGetAnalyzerReference(Solution solution) { var project = solution.GetProject(ProjectId); if (project == null) { return null; } var canonicalName = _item.CanonicalName; var analyzerFilePath = CpsUtilities.ExtractAnalyzerFilePath(_projectDirectoryPath, canonicalName); if (string.IsNullOrEmpty(analyzerFilePath)) { return null; } return project.AnalyzerReferences.FirstOrDefault(r => string.Equals(r.FullPath, analyzerFilePath, StringComparison.OrdinalIgnoreCase)); } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/Diagnostics/DiagnosticMode.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Diagnostics { internal enum DiagnosticMode { /// <summary> /// Push diagnostics. Roslyn/LSP is responsible for aggregating internal diagnostic notifications and pushing /// those out to either VS or the LSP push diagnostic system. /// </summary> Push, /// <summary> /// Pull diagnostics. Roslyn/LSP is responsible for aggregating internal diagnostic notifications and /// responding to LSP pull requests for them. /// </summary> Pull, /// <summary> /// Default mode - when the option is set to default we use a feature flag to determine if we're /// is in <see cref="Push"/> or <see cref="Pull"/> /// </summary> 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. namespace Microsoft.CodeAnalysis.Diagnostics { internal enum DiagnosticMode { /// <summary> /// Push diagnostics. Roslyn/LSP is responsible for aggregating internal diagnostic notifications and pushing /// those out to either VS or the LSP push diagnostic system. /// </summary> Push, /// <summary> /// Pull diagnostics. Roslyn/LSP is responsible for aggregating internal diagnostic notifications and /// responding to LSP pull requests for them. /// </summary> Pull, /// <summary> /// Default mode - when the option is set to default we use a feature flag to determine if we're /// is in <see cref="Push"/> or <see cref="Pull"/> /// </summary> Default, } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Test/Core/Platform/Desktop/Exceptions.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 #if NET472 using System; using System.Collections.Generic; using System.Runtime.Serialization; using Microsoft.CodeAnalysis; using static Roslyn.Test.Utilities.ExceptionHelper; namespace Roslyn.Test.Utilities.Desktop { [Serializable] public class RuntimePeVerifyException : Exception { public string Output { get; } public string ExePath { get; } protected RuntimePeVerifyException(SerializationInfo info, StreamingContext context) : base(info, context) { Output = info.GetString(nameof(Output)); ExePath = info.GetString(nameof(ExePath)); } public RuntimePeVerifyException(string output, string exePath) : base(GetMessageFromResult(output, exePath)) { Output = output; ExePath = exePath; } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue(nameof(Output), Output); info.AddValue(nameof(ExePath), ExePath); } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #if NET472 using System; using System.Collections.Generic; using System.Runtime.Serialization; using Microsoft.CodeAnalysis; using static Roslyn.Test.Utilities.ExceptionHelper; namespace Roslyn.Test.Utilities.Desktop { [Serializable] public class RuntimePeVerifyException : Exception { public string Output { get; } public string ExePath { get; } protected RuntimePeVerifyException(SerializationInfo info, StreamingContext context) : base(info, context) { Output = info.GetString(nameof(Output)); ExePath = info.GetString(nameof(ExePath)); } public RuntimePeVerifyException(string output, string exePath) : base(GetMessageFromResult(output, exePath)) { Output = output; ExePath = exePath; } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue(nameof(Output), Output); info.AddValue(nameof(ExePath), ExePath); } } } #endif
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Remote/ServiceHub/Services/ExtensionMethodImportCompletion/RemoteExtensionMethodImportCompletionService.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.Completion.Providers; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { internal sealed class RemoteExtensionMethodImportCompletionService : BrokeredServiceBase, IRemoteExtensionMethodImportCompletionService { internal sealed class Factory : FactoryBase<IRemoteExtensionMethodImportCompletionService> { protected override IRemoteExtensionMethodImportCompletionService CreateService(in ServiceConstructionArguments arguments) => new RemoteExtensionMethodImportCompletionService(arguments); } public RemoteExtensionMethodImportCompletionService(in ServiceConstructionArguments arguments) : base(arguments) { } public ValueTask<SerializableUnimportedExtensionMethods> GetUnimportedExtensionMethodsAsync( PinnedSolutionInfo solutionInfo, DocumentId documentId, int position, string receiverTypeSymbolKeyData, ImmutableArray<string> namespaceInScope, ImmutableArray<string> targetTypesSymbolKeyData, bool forceIndexCreation, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var document = solution.GetDocument(documentId)!; var compilation = await document.Project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var symbol = SymbolKey.ResolveString(receiverTypeSymbolKeyData, compilation, cancellationToken: cancellationToken).GetAnySymbol(); if (symbol is ITypeSymbol receiverTypeSymbol) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var namespaceInScopeSet = new HashSet<string>(namespaceInScope, syntaxFacts.StringComparer); var targetTypes = targetTypesSymbolKeyData .Select(symbolKey => SymbolKey.ResolveString(symbolKey, compilation, cancellationToken: cancellationToken).GetAnySymbol() as ITypeSymbol) .WhereNotNull().ToImmutableArray(); return await ExtensionMethodImportCompletionHelper.GetUnimportedExtensionMethodsInCurrentProcessAsync( document, position, receiverTypeSymbol, namespaceInScopeSet, targetTypes, forceIndexCreation, cancellationToken).ConfigureAwait(false); } return new SerializableUnimportedExtensionMethods(ImmutableArray<SerializableImportCompletionItem>.Empty, isPartialResult: false, getSymbolsTicks: 0, createItemsTicks: 0); }, 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; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { internal sealed class RemoteExtensionMethodImportCompletionService : BrokeredServiceBase, IRemoteExtensionMethodImportCompletionService { internal sealed class Factory : FactoryBase<IRemoteExtensionMethodImportCompletionService> { protected override IRemoteExtensionMethodImportCompletionService CreateService(in ServiceConstructionArguments arguments) => new RemoteExtensionMethodImportCompletionService(arguments); } public RemoteExtensionMethodImportCompletionService(in ServiceConstructionArguments arguments) : base(arguments) { } public ValueTask<SerializableUnimportedExtensionMethods> GetUnimportedExtensionMethodsAsync( PinnedSolutionInfo solutionInfo, DocumentId documentId, int position, string receiverTypeSymbolKeyData, ImmutableArray<string> namespaceInScope, ImmutableArray<string> targetTypesSymbolKeyData, bool forceIndexCreation, CancellationToken cancellationToken) { return RunServiceAsync(async cancellationToken => { var solution = await GetSolutionAsync(solutionInfo, cancellationToken).ConfigureAwait(false); var document = solution.GetDocument(documentId)!; var compilation = await document.Project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var symbol = SymbolKey.ResolveString(receiverTypeSymbolKeyData, compilation, cancellationToken: cancellationToken).GetAnySymbol(); if (symbol is ITypeSymbol receiverTypeSymbol) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var namespaceInScopeSet = new HashSet<string>(namespaceInScope, syntaxFacts.StringComparer); var targetTypes = targetTypesSymbolKeyData .Select(symbolKey => SymbolKey.ResolveString(symbolKey, compilation, cancellationToken: cancellationToken).GetAnySymbol() as ITypeSymbol) .WhereNotNull().ToImmutableArray(); return await ExtensionMethodImportCompletionHelper.GetUnimportedExtensionMethodsInCurrentProcessAsync( document, position, receiverTypeSymbol, namespaceInScopeSet, targetTypes, forceIndexCreation, cancellationToken).ConfigureAwait(false); } return new SerializableUnimportedExtensionMethods(ImmutableArray<SerializableImportCompletionItem>.Empty, isPartialResult: false, getSymbolsTicks: 0, createItemsTicks: 0); }, cancellationToken); } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/BoundTree/ConversionGroup.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A group is a common instance referenced by all BoundConversion instances /// generated from a single Conversion. The group is used by NullableWalker to /// determine which BoundConversion nodes should be considered as a unit. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal sealed class ConversionGroup { internal ConversionGroup(Conversion conversion, TypeWithAnnotations explicitType = default) { Conversion = conversion; ExplicitType = explicitType; } /// <summary> /// True if the conversion is an explicit conversion. /// </summary> internal bool IsExplicitConversion => ExplicitType.HasType; /// <summary> /// The conversion (from Conversions.ClassifyConversionFromExpression for /// instance) from which all BoundConversions in the group were created. /// </summary> internal readonly Conversion Conversion; /// <summary> /// The target type of the conversion specified explicitly in source, /// or null if not an explicit conversion. /// </summary> internal readonly TypeWithAnnotations ExplicitType; #if DEBUG private static int _nextId; private readonly int _id = _nextId++; internal string GetDebuggerDisplay() { var str = $"#{_id} {Conversion}"; if (ExplicitType.HasType) { str += $" ({ExplicitType})"; } return str; } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A group is a common instance referenced by all BoundConversion instances /// generated from a single Conversion. The group is used by NullableWalker to /// determine which BoundConversion nodes should be considered as a unit. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal sealed class ConversionGroup { internal ConversionGroup(Conversion conversion, TypeWithAnnotations explicitType = default) { Conversion = conversion; ExplicitType = explicitType; } /// <summary> /// True if the conversion is an explicit conversion. /// </summary> internal bool IsExplicitConversion => ExplicitType.HasType; /// <summary> /// The conversion (from Conversions.ClassifyConversionFromExpression for /// instance) from which all BoundConversions in the group were created. /// </summary> internal readonly Conversion Conversion; /// <summary> /// The target type of the conversion specified explicitly in source, /// or null if not an explicit conversion. /// </summary> internal readonly TypeWithAnnotations ExplicitType; #if DEBUG private static int _nextId; private readonly int _id = _nextId++; internal string GetDebuggerDisplay() { var str = $"#{_id} {Conversion}"; if (ExplicitType.HasType) { str += $" ({ExplicitType})"; } return str; } #endif } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Analyzers/CSharp/Analyzers/UseIsNullCheck/CSharpUseIsNullCheckForCastAndEqualityOperatorDiagnosticAnalyzer.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 Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.UseIsNullCheck; namespace Microsoft.CodeAnalysis.CSharp.UseIsNullCheck { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpUseIsNullCheckForCastAndEqualityOperatorDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { private static readonly ImmutableDictionary<string, string> s_properties = ImmutableDictionary<string, string>.Empty.Add(UseIsNullConstants.Kind, UseIsNullConstants.CastAndEqualityKey); public CSharpUseIsNullCheckForCastAndEqualityOperatorDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseIsNullCheckDiagnosticId, EnforceOnBuildValues.UseIsNullCheck, CodeStyleOptions2.PreferIsNullCheckOverReferenceEqualityMethod, CSharpAnalyzersResources.Use_is_null_check, new LocalizableResourceString(nameof(AnalyzersResources.Null_check_can_be_simplified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) => context.RegisterCompilationStartAction(context => { if (((CSharpCompilation)context.Compilation).LanguageVersion < LanguageVersion.CSharp7) { return; } context.RegisterSyntaxNodeAction(n => AnalyzeSyntax(n), SyntaxKind.EqualsExpression, SyntaxKind.NotEqualsExpression); }); private void AnalyzeSyntax(SyntaxNodeAnalysisContext context) { var cancellationToken = context.CancellationToken; var semanticModel = context.SemanticModel; var syntaxTree = semanticModel.SyntaxTree; var option = context.Options.GetOption(CodeStyleOptions2.PreferIsNullCheckOverReferenceEqualityMethod, semanticModel.Language, syntaxTree, cancellationToken); if (!option.Value) { return; } var binaryExpression = (BinaryExpressionSyntax)context.Node; if (!IsObjectCastAndNullCheck(semanticModel, binaryExpression.Left, binaryExpression.Right) && !IsObjectCastAndNullCheck(semanticModel, binaryExpression.Right, binaryExpression.Left)) { return; } var severity = option.Notification.Severity; context.ReportDiagnostic( DiagnosticHelper.Create( Descriptor, binaryExpression.GetLocation(), severity, additionalLocations: null, s_properties)); } private static bool IsObjectCastAndNullCheck( SemanticModel semanticModel, ExpressionSyntax left, ExpressionSyntax right) { if (left is CastExpressionSyntax castExpression && right.IsKind(SyntaxKind.NullLiteralExpression)) { // make sure it's a cast to object, and that the thing we're casting actually has a type. if (semanticModel.GetTypeInfo(castExpression.Type).Type?.SpecialType == SpecialType.System_Object) { var expressionType = semanticModel.GetTypeInfo(castExpression.Expression).Type; if (expressionType != null) { if (expressionType is ITypeParameterSymbol typeParameter && !typeParameter.HasReferenceTypeConstraint) { return false; } return true; } } } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.UseIsNullCheck; namespace Microsoft.CodeAnalysis.CSharp.UseIsNullCheck { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpUseIsNullCheckForCastAndEqualityOperatorDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { private static readonly ImmutableDictionary<string, string> s_properties = ImmutableDictionary<string, string>.Empty.Add(UseIsNullConstants.Kind, UseIsNullConstants.CastAndEqualityKey); public CSharpUseIsNullCheckForCastAndEqualityOperatorDiagnosticAnalyzer() : base(IDEDiagnosticIds.UseIsNullCheckDiagnosticId, EnforceOnBuildValues.UseIsNullCheck, CodeStyleOptions2.PreferIsNullCheckOverReferenceEqualityMethod, CSharpAnalyzersResources.Use_is_null_check, new LocalizableResourceString(nameof(AnalyzersResources.Null_check_can_be_simplified), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) => context.RegisterCompilationStartAction(context => { if (((CSharpCompilation)context.Compilation).LanguageVersion < LanguageVersion.CSharp7) { return; } context.RegisterSyntaxNodeAction(n => AnalyzeSyntax(n), SyntaxKind.EqualsExpression, SyntaxKind.NotEqualsExpression); }); private void AnalyzeSyntax(SyntaxNodeAnalysisContext context) { var cancellationToken = context.CancellationToken; var semanticModel = context.SemanticModel; var syntaxTree = semanticModel.SyntaxTree; var option = context.Options.GetOption(CodeStyleOptions2.PreferIsNullCheckOverReferenceEqualityMethod, semanticModel.Language, syntaxTree, cancellationToken); if (!option.Value) { return; } var binaryExpression = (BinaryExpressionSyntax)context.Node; if (!IsObjectCastAndNullCheck(semanticModel, binaryExpression.Left, binaryExpression.Right) && !IsObjectCastAndNullCheck(semanticModel, binaryExpression.Right, binaryExpression.Left)) { return; } var severity = option.Notification.Severity; context.ReportDiagnostic( DiagnosticHelper.Create( Descriptor, binaryExpression.GetLocation(), severity, additionalLocations: null, s_properties)); } private static bool IsObjectCastAndNullCheck( SemanticModel semanticModel, ExpressionSyntax left, ExpressionSyntax right) { if (left is CastExpressionSyntax castExpression && right.IsKind(SyntaxKind.NullLiteralExpression)) { // make sure it's a cast to object, and that the thing we're casting actually has a type. if (semanticModel.GetTypeInfo(castExpression.Type).Type?.SpecialType == SpecialType.System_Object) { var expressionType = semanticModel.GetTypeInfo(castExpression.Expression).Type; if (expressionType != null) { if (expressionType is ITypeParameterSymbol typeParameter && !typeParameter.HasReferenceTypeConstraint) { return false; } return true; } } } return false; } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/DiagnosticsTestUtilities/SplitComments/AbstractSplitCommentCommandHandlerTests.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.Editor.CSharp.SplitStringLiteral; using Microsoft.CodeAnalysis.Editor.Implementation.SplitComment; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Operations; using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.Formatting.FormattingOptions; namespace Microsoft.CodeAnalysis.Editor.UnitTests.SplitComment { public abstract class AbstractSplitCommentCommandHandlerTests { protected abstract TestWorkspace CreateWorkspace(string markup); /// <summary> /// verifyUndo is needed because of https://github.com/dotnet/roslyn/issues/28033 /// Most tests will continue to verifyUndo, but select tests will skip it due to /// this known test infrastructure issue. This bug does not represent a product /// failure. /// </summary> private void TestWorker( string inputMarkup, string? expectedOutputMarkup, Action callback, bool enabled, bool useTabs) { if (useTabs) { // Make sure the tests seem well formed (i.e. no one accidentally replaced the tabs in them with spaces. Assert.True(inputMarkup.Contains("\t")); if (expectedOutputMarkup != null) Assert.True(expectedOutputMarkup.Contains("\t")); } using var workspace = this.CreateWorkspace(inputMarkup); var language = workspace.Projects.Single().Language; workspace.SetOptions( workspace.Options.WithChangedOption(FormattingOptions.UseTabs, language, useTabs) .WithChangedOption(SplitCommentOptions.Enabled, language, enabled)); var document = workspace.Documents.Single(); var view = document.GetTextView(); var originalSnapshot = view.TextBuffer.CurrentSnapshot; var originalSelections = document.SelectedSpans; var snapshotSpans = new List<SnapshotSpan>(); foreach (var selection in originalSelections) snapshotSpans.Add(new SnapshotSpan(originalSnapshot, new Span(selection.Start, selection.Length))); view.SetMultiSelection(snapshotSpans); var undoHistoryRegistry = workspace.GetService<ITextUndoHistoryRegistry>(); var commandHandler = workspace.ExportProvider.GetCommandHandler<SplitCommentCommandHandler>(nameof(SplitCommentCommandHandler)); if (!commandHandler.ExecuteCommand(new ReturnKeyCommandArgs(view, view.TextBuffer), TestCommandExecutionContext.Create())) { callback(); } if (expectedOutputMarkup != null) { MarkupTestFile.GetSpans(expectedOutputMarkup, out var expectedOutput, out ImmutableArray<TextSpan> expectedSpans); Assert.Equal(expectedOutput, view.TextBuffer.CurrentSnapshot.AsText().ToString()); // Ensure that after undo we go back to where we were to begin with. var history = undoHistoryRegistry.GetHistory(document.GetTextBuffer()); history.Undo(count: originalSelections.Count); var currentSnapshot = document.GetTextBuffer().CurrentSnapshot; Assert.Equal(originalSnapshot.GetText(), currentSnapshot.GetText()); } } /// <summary> /// verifyUndo is needed because of https://github.com/dotnet/roslyn/issues/28033 /// Most tests will continue to verifyUndo, but select tests will skip it due to /// this known test infrastructure issue. This bug does not represent a product /// failure. /// </summary> protected void TestHandled(string inputMarkup, string expectedOutputMarkup, bool enabled = true, bool useTabs = false) { TestWorker( inputMarkup, expectedOutputMarkup, callback: () => { Assert.True(false, "Should not reach here."); }, enabled, useTabs); } protected void TestNotHandled(string inputMarkup, bool enabled = true, bool useTabs = false) { var notHandled = false; TestWorker( inputMarkup, null, callback: () => { notHandled = true; }, enabled, useTabs); Assert.True(notHandled); } } }
// Licensed to the .NET Foundation under one or more 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.Editor.CSharp.SplitStringLiteral; using Microsoft.CodeAnalysis.Editor.Implementation.SplitComment; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Text.Operations; using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.Formatting.FormattingOptions; namespace Microsoft.CodeAnalysis.Editor.UnitTests.SplitComment { public abstract class AbstractSplitCommentCommandHandlerTests { protected abstract TestWorkspace CreateWorkspace(string markup); /// <summary> /// verifyUndo is needed because of https://github.com/dotnet/roslyn/issues/28033 /// Most tests will continue to verifyUndo, but select tests will skip it due to /// this known test infrastructure issue. This bug does not represent a product /// failure. /// </summary> private void TestWorker( string inputMarkup, string? expectedOutputMarkup, Action callback, bool enabled, bool useTabs) { if (useTabs) { // Make sure the tests seem well formed (i.e. no one accidentally replaced the tabs in them with spaces. Assert.True(inputMarkup.Contains("\t")); if (expectedOutputMarkup != null) Assert.True(expectedOutputMarkup.Contains("\t")); } using var workspace = this.CreateWorkspace(inputMarkup); var language = workspace.Projects.Single().Language; workspace.SetOptions( workspace.Options.WithChangedOption(FormattingOptions.UseTabs, language, useTabs) .WithChangedOption(SplitCommentOptions.Enabled, language, enabled)); var document = workspace.Documents.Single(); var view = document.GetTextView(); var originalSnapshot = view.TextBuffer.CurrentSnapshot; var originalSelections = document.SelectedSpans; var snapshotSpans = new List<SnapshotSpan>(); foreach (var selection in originalSelections) snapshotSpans.Add(new SnapshotSpan(originalSnapshot, new Span(selection.Start, selection.Length))); view.SetMultiSelection(snapshotSpans); var undoHistoryRegistry = workspace.GetService<ITextUndoHistoryRegistry>(); var commandHandler = workspace.ExportProvider.GetCommandHandler<SplitCommentCommandHandler>(nameof(SplitCommentCommandHandler)); if (!commandHandler.ExecuteCommand(new ReturnKeyCommandArgs(view, view.TextBuffer), TestCommandExecutionContext.Create())) { callback(); } if (expectedOutputMarkup != null) { MarkupTestFile.GetSpans(expectedOutputMarkup, out var expectedOutput, out ImmutableArray<TextSpan> expectedSpans); Assert.Equal(expectedOutput, view.TextBuffer.CurrentSnapshot.AsText().ToString()); // Ensure that after undo we go back to where we were to begin with. var history = undoHistoryRegistry.GetHistory(document.GetTextBuffer()); history.Undo(count: originalSelections.Count); var currentSnapshot = document.GetTextBuffer().CurrentSnapshot; Assert.Equal(originalSnapshot.GetText(), currentSnapshot.GetText()); } } /// <summary> /// verifyUndo is needed because of https://github.com/dotnet/roslyn/issues/28033 /// Most tests will continue to verifyUndo, but select tests will skip it due to /// this known test infrastructure issue. This bug does not represent a product /// failure. /// </summary> protected void TestHandled(string inputMarkup, string expectedOutputMarkup, bool enabled = true, bool useTabs = false) { TestWorker( inputMarkup, expectedOutputMarkup, callback: () => { Assert.True(false, "Should not reach here."); }, enabled, useTabs); } protected void TestNotHandled(string inputMarkup, bool enabled = true, bool useTabs = false) { var notHandled = false; TestWorker( inputMarkup, null, callback: () => { notHandled = true; }, enabled, useTabs); Assert.True(notHandled); } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/Tagging/TaggerCaretChangeBehavior.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.CodeAnalysis.Editor.Tagging { /// <summary> /// Flags that affect how the tagger infrastructure responds to caret changes. /// </summary> [Flags] internal enum TaggerCaretChangeBehavior { /// <summary> /// No special caret change behavior. /// </summary> None = 0, /// <summary> /// If the caret moves outside of a tag, immediately remove all existing tags. /// </summary> RemoveAllTagsOnCaretMoveOutsideOfTag = 1 << 0, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.CodeAnalysis.Editor.Tagging { /// <summary> /// Flags that affect how the tagger infrastructure responds to caret changes. /// </summary> [Flags] internal enum TaggerCaretChangeBehavior { /// <summary> /// No special caret change behavior. /// </summary> None = 0, /// <summary> /// If the caret moves outside of a tag, immediately remove all existing tags. /// </summary> RemoveAllTagsOnCaretMoveOutsideOfTag = 1 << 0, } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/FindUsages/DefinitionItem.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.Threading; using Microsoft.CodeAnalysis.Tags; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindUsages { /// <summary> /// Information about a symbol's definition that can be displayed in an editor /// and used for navigation. /// /// Standard implmentations can be obtained through the various <see cref="DefinitionItem"/>.Create /// overloads. /// /// Subclassing is also supported for scenarios that fall outside the bounds of /// these common cases. /// </summary> internal abstract partial class DefinitionItem { /// <summary> /// The definition item corresponding to the initial symbol the user was trying to find. This item should get /// prominent placement in the final UI for the user. /// </summary> internal const string Primary = nameof(Primary); // Existing behavior is to do up to two lookups for 3rd party navigation for FAR. One // for the symbol itself and one for a 'fallback' symbol. For example, if we're FARing // on a constructor, then the fallback symbol will be the actual type that the constructor // is contained within. internal const string RQNameKey1 = nameof(RQNameKey1); internal const string RQNameKey2 = nameof(RQNameKey2); /// <summary> /// For metadata symbols we encode information in the <see cref="Properties"/> so we can /// retrieve the symbol later on when navigating. This is needed so that we can go to /// metadata-as-source for metadata symbols. We need to store the <see cref="SymbolKey"/> /// for the symbol and the project ID that originated the symbol. With these we can correctly recover the symbol. /// </summary> private const string MetadataSymbolKey = nameof(MetadataSymbolKey); private const string MetadataSymbolOriginatingProjectIdGuid = nameof(MetadataSymbolOriginatingProjectIdGuid); private const string MetadataSymbolOriginatingProjectIdDebugName = nameof(MetadataSymbolOriginatingProjectIdDebugName); /// <summary> /// If this item is something that cannot be navigated to. We store this in our /// <see cref="Properties"/> to act as an explicit marker that navigation is not possible. /// </summary> private const string NonNavigable = nameof(NonNavigable); /// <summary> /// Descriptive tags from <see cref="WellKnownTags"/>. These tags may influence how the /// item is displayed. /// </summary> public ImmutableArray<string> Tags { get; } /// <summary> /// Additional properties that can be attached to the definition for clients that want to /// keep track of additional data. /// </summary> public ImmutableDictionary<string, string> Properties { get; } /// <summary> /// Additional diplayable properties that can be attached to the definition for clients that want to /// display additional data. /// </summary> public ImmutableDictionary<string, string> DisplayableProperties { get; } /// <summary> /// The DisplayParts just for the name of this definition. Generally used only for /// error messages. /// </summary> public ImmutableArray<TaggedText> NameDisplayParts { get; } /// <summary> /// The full display parts for this definition. Displayed in a classified /// manner when possible. /// </summary> public ImmutableArray<TaggedText> DisplayParts { get; } /// <summary> /// Where the location originally came from (for example, the containing assembly or /// project name). May be used in the presentation of a definition. /// </summary> public ImmutableArray<TaggedText> OriginationParts { get; } /// <summary> /// Additional locations to present in the UI. A definition may have multiple locations /// for cases like partial types/members. /// </summary> public ImmutableArray<DocumentSpan> SourceSpans { get; } /// <summary> /// Whether or not this definition should be presented if we never found any references to /// it. For example, when searching for a property, the FindReferences engine will cascade /// to the accessors in case any code specifically called those accessors (can happen in /// cross-language cases). However, in the normal case where there were no calls specifically /// to the accessor, we would not want to display them in the UI. /// /// For most definitions we will want to display them, even if no references were found. /// This property allows for this customization in behavior. /// </summary> public bool DisplayIfNoReferences { get; } internal abstract bool IsExternal { get; } // F# uses this protected DefinitionItem( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<TaggedText> nameDisplayParts, ImmutableArray<TaggedText> originationParts, ImmutableArray<DocumentSpan> sourceSpans, ImmutableDictionary<string, string> properties, bool displayIfNoReferences) : this( tags, displayParts, nameDisplayParts, originationParts, sourceSpans, properties, ImmutableDictionary<string, string>.Empty, displayIfNoReferences) { } protected DefinitionItem( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<TaggedText> nameDisplayParts, ImmutableArray<TaggedText> originationParts, ImmutableArray<DocumentSpan> sourceSpans, ImmutableDictionary<string, string> properties, ImmutableDictionary<string, string> displayableProperties, bool displayIfNoReferences) { Tags = tags; DisplayParts = displayParts; NameDisplayParts = nameDisplayParts.IsDefaultOrEmpty ? displayParts : nameDisplayParts; OriginationParts = originationParts.NullToEmpty(); SourceSpans = sourceSpans.NullToEmpty(); Properties = properties ?? ImmutableDictionary<string, string>.Empty; DisplayableProperties = displayableProperties ?? ImmutableDictionary<string, string>.Empty; DisplayIfNoReferences = displayIfNoReferences; if (Properties.ContainsKey(MetadataSymbolKey)) { Contract.ThrowIfFalse(Properties.ContainsKey(MetadataSymbolOriginatingProjectIdGuid)); Contract.ThrowIfFalse(Properties.ContainsKey(MetadataSymbolOriginatingProjectIdDebugName)); } } public abstract bool CanNavigateTo(Workspace workspace, CancellationToken cancellationToken); public abstract bool TryNavigateTo(Workspace workspace, bool showInPreviewTab, bool activateTab, CancellationToken cancellationToken); public static DefinitionItem Create( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, DocumentSpan sourceSpan, ImmutableArray<TaggedText> nameDisplayParts = default, bool displayIfNoReferences = true) { return Create( tags, displayParts, ImmutableArray.Create(sourceSpan), nameDisplayParts, displayIfNoReferences); } // Kept around for binary compat with F#/TypeScript. public static DefinitionItem Create( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<DocumentSpan> sourceSpans, ImmutableArray<TaggedText> nameDisplayParts, bool displayIfNoReferences) { return Create( tags, displayParts, sourceSpans, nameDisplayParts, properties: null, displayableProperties: ImmutableDictionary<string, string>.Empty, displayIfNoReferences: displayIfNoReferences); } public static DefinitionItem Create( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<DocumentSpan> sourceSpans, ImmutableArray<TaggedText> nameDisplayParts = default, ImmutableDictionary<string, string> properties = null, bool displayIfNoReferences = true) { return Create(tags, displayParts, sourceSpans, nameDisplayParts, properties, ImmutableDictionary<string, string>.Empty, displayIfNoReferences); } public static DefinitionItem Create( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<DocumentSpan> sourceSpans, ImmutableArray<TaggedText> nameDisplayParts = default, ImmutableDictionary<string, string> properties = null, ImmutableDictionary<string, string> displayableProperties = null, bool displayIfNoReferences = true) { if (sourceSpans.Length == 0) { throw new ArgumentException($"{nameof(sourceSpans)} cannot be empty."); } var firstDocument = sourceSpans[0].Document; var originationParts = ImmutableArray.Create( new TaggedText(TextTags.Text, firstDocument.Project.Name)); return new DefaultDefinitionItem( tags, displayParts, nameDisplayParts, originationParts, sourceSpans, properties, displayableProperties, displayIfNoReferences); } internal static DefinitionItem CreateMetadataDefinition( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<TaggedText> nameDisplayParts, Solution solution, ISymbol symbol, ImmutableDictionary<string, string> properties = null, bool displayIfNoReferences = true) { properties ??= ImmutableDictionary<string, string>.Empty; var symbolKey = symbol.GetSymbolKey().ToString(); var projectId = solution.GetOriginatingProjectId(symbol); Contract.ThrowIfNull(projectId); properties = properties.Add(MetadataSymbolKey, symbolKey) .Add(MetadataSymbolOriginatingProjectIdGuid, projectId.Id.ToString()) .Add(MetadataSymbolOriginatingProjectIdDebugName, projectId.DebugName); var originationParts = GetOriginationParts(symbol); return new DefaultDefinitionItem( tags, displayParts, nameDisplayParts, originationParts, sourceSpans: ImmutableArray<DocumentSpan>.Empty, properties: properties, displayableProperties: ImmutableDictionary<string, string>.Empty, displayIfNoReferences: displayIfNoReferences); } // Kept around for binary compat with F#/TypeScript. public static DefinitionItem CreateNonNavigableItem( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<TaggedText> originationParts, bool displayIfNoReferences) { return CreateNonNavigableItem( tags, displayParts, originationParts, properties: null, displayIfNoReferences: displayIfNoReferences); } public static DefinitionItem CreateNonNavigableItem( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<TaggedText> originationParts = default, ImmutableDictionary<string, string> properties = null, bool displayIfNoReferences = true) { properties ??= ImmutableDictionary<string, string>.Empty; properties = properties.Add(NonNavigable, ""); return new DefaultDefinitionItem( tags: tags, displayParts: displayParts, nameDisplayParts: ImmutableArray<TaggedText>.Empty, originationParts: originationParts, sourceSpans: ImmutableArray<DocumentSpan>.Empty, properties: properties, displayableProperties: ImmutableDictionary<string, string>.Empty, displayIfNoReferences: displayIfNoReferences); } internal static ImmutableArray<TaggedText> GetOriginationParts(ISymbol symbol) { // We don't show an origination location for a namespace because it can span over // both metadata assemblies and source projects. // // Otherwise show the assembly this symbol came from as the Origination of // the DefinitionItem. if (symbol.Kind != SymbolKind.Namespace) { var assemblyName = symbol.ContainingAssembly?.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat); if (!string.IsNullOrWhiteSpace(assemblyName)) { return ImmutableArray.Create(new TaggedText(TextTags.Assembly, assemblyName)); } } return ImmutableArray<TaggedText>.Empty; } } }
// Licensed to the .NET Foundation under one or more 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.Threading; using Microsoft.CodeAnalysis.Tags; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindUsages { /// <summary> /// Information about a symbol's definition that can be displayed in an editor /// and used for navigation. /// /// Standard implmentations can be obtained through the various <see cref="DefinitionItem"/>.Create /// overloads. /// /// Subclassing is also supported for scenarios that fall outside the bounds of /// these common cases. /// </summary> internal abstract partial class DefinitionItem { /// <summary> /// The definition item corresponding to the initial symbol the user was trying to find. This item should get /// prominent placement in the final UI for the user. /// </summary> internal const string Primary = nameof(Primary); // Existing behavior is to do up to two lookups for 3rd party navigation for FAR. One // for the symbol itself and one for a 'fallback' symbol. For example, if we're FARing // on a constructor, then the fallback symbol will be the actual type that the constructor // is contained within. internal const string RQNameKey1 = nameof(RQNameKey1); internal const string RQNameKey2 = nameof(RQNameKey2); /// <summary> /// For metadata symbols we encode information in the <see cref="Properties"/> so we can /// retrieve the symbol later on when navigating. This is needed so that we can go to /// metadata-as-source for metadata symbols. We need to store the <see cref="SymbolKey"/> /// for the symbol and the project ID that originated the symbol. With these we can correctly recover the symbol. /// </summary> private const string MetadataSymbolKey = nameof(MetadataSymbolKey); private const string MetadataSymbolOriginatingProjectIdGuid = nameof(MetadataSymbolOriginatingProjectIdGuid); private const string MetadataSymbolOriginatingProjectIdDebugName = nameof(MetadataSymbolOriginatingProjectIdDebugName); /// <summary> /// If this item is something that cannot be navigated to. We store this in our /// <see cref="Properties"/> to act as an explicit marker that navigation is not possible. /// </summary> private const string NonNavigable = nameof(NonNavigable); /// <summary> /// Descriptive tags from <see cref="WellKnownTags"/>. These tags may influence how the /// item is displayed. /// </summary> public ImmutableArray<string> Tags { get; } /// <summary> /// Additional properties that can be attached to the definition for clients that want to /// keep track of additional data. /// </summary> public ImmutableDictionary<string, string> Properties { get; } /// <summary> /// Additional diplayable properties that can be attached to the definition for clients that want to /// display additional data. /// </summary> public ImmutableDictionary<string, string> DisplayableProperties { get; } /// <summary> /// The DisplayParts just for the name of this definition. Generally used only for /// error messages. /// </summary> public ImmutableArray<TaggedText> NameDisplayParts { get; } /// <summary> /// The full display parts for this definition. Displayed in a classified /// manner when possible. /// </summary> public ImmutableArray<TaggedText> DisplayParts { get; } /// <summary> /// Where the location originally came from (for example, the containing assembly or /// project name). May be used in the presentation of a definition. /// </summary> public ImmutableArray<TaggedText> OriginationParts { get; } /// <summary> /// Additional locations to present in the UI. A definition may have multiple locations /// for cases like partial types/members. /// </summary> public ImmutableArray<DocumentSpan> SourceSpans { get; } /// <summary> /// Whether or not this definition should be presented if we never found any references to /// it. For example, when searching for a property, the FindReferences engine will cascade /// to the accessors in case any code specifically called those accessors (can happen in /// cross-language cases). However, in the normal case where there were no calls specifically /// to the accessor, we would not want to display them in the UI. /// /// For most definitions we will want to display them, even if no references were found. /// This property allows for this customization in behavior. /// </summary> public bool DisplayIfNoReferences { get; } internal abstract bool IsExternal { get; } // F# uses this protected DefinitionItem( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<TaggedText> nameDisplayParts, ImmutableArray<TaggedText> originationParts, ImmutableArray<DocumentSpan> sourceSpans, ImmutableDictionary<string, string> properties, bool displayIfNoReferences) : this( tags, displayParts, nameDisplayParts, originationParts, sourceSpans, properties, ImmutableDictionary<string, string>.Empty, displayIfNoReferences) { } protected DefinitionItem( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<TaggedText> nameDisplayParts, ImmutableArray<TaggedText> originationParts, ImmutableArray<DocumentSpan> sourceSpans, ImmutableDictionary<string, string> properties, ImmutableDictionary<string, string> displayableProperties, bool displayIfNoReferences) { Tags = tags; DisplayParts = displayParts; NameDisplayParts = nameDisplayParts.IsDefaultOrEmpty ? displayParts : nameDisplayParts; OriginationParts = originationParts.NullToEmpty(); SourceSpans = sourceSpans.NullToEmpty(); Properties = properties ?? ImmutableDictionary<string, string>.Empty; DisplayableProperties = displayableProperties ?? ImmutableDictionary<string, string>.Empty; DisplayIfNoReferences = displayIfNoReferences; if (Properties.ContainsKey(MetadataSymbolKey)) { Contract.ThrowIfFalse(Properties.ContainsKey(MetadataSymbolOriginatingProjectIdGuid)); Contract.ThrowIfFalse(Properties.ContainsKey(MetadataSymbolOriginatingProjectIdDebugName)); } } public abstract bool CanNavigateTo(Workspace workspace, CancellationToken cancellationToken); public abstract bool TryNavigateTo(Workspace workspace, bool showInPreviewTab, bool activateTab, CancellationToken cancellationToken); public static DefinitionItem Create( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, DocumentSpan sourceSpan, ImmutableArray<TaggedText> nameDisplayParts = default, bool displayIfNoReferences = true) { return Create( tags, displayParts, ImmutableArray.Create(sourceSpan), nameDisplayParts, displayIfNoReferences); } // Kept around for binary compat with F#/TypeScript. public static DefinitionItem Create( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<DocumentSpan> sourceSpans, ImmutableArray<TaggedText> nameDisplayParts, bool displayIfNoReferences) { return Create( tags, displayParts, sourceSpans, nameDisplayParts, properties: null, displayableProperties: ImmutableDictionary<string, string>.Empty, displayIfNoReferences: displayIfNoReferences); } public static DefinitionItem Create( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<DocumentSpan> sourceSpans, ImmutableArray<TaggedText> nameDisplayParts = default, ImmutableDictionary<string, string> properties = null, bool displayIfNoReferences = true) { return Create(tags, displayParts, sourceSpans, nameDisplayParts, properties, ImmutableDictionary<string, string>.Empty, displayIfNoReferences); } public static DefinitionItem Create( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<DocumentSpan> sourceSpans, ImmutableArray<TaggedText> nameDisplayParts = default, ImmutableDictionary<string, string> properties = null, ImmutableDictionary<string, string> displayableProperties = null, bool displayIfNoReferences = true) { if (sourceSpans.Length == 0) { throw new ArgumentException($"{nameof(sourceSpans)} cannot be empty."); } var firstDocument = sourceSpans[0].Document; var originationParts = ImmutableArray.Create( new TaggedText(TextTags.Text, firstDocument.Project.Name)); return new DefaultDefinitionItem( tags, displayParts, nameDisplayParts, originationParts, sourceSpans, properties, displayableProperties, displayIfNoReferences); } internal static DefinitionItem CreateMetadataDefinition( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<TaggedText> nameDisplayParts, Solution solution, ISymbol symbol, ImmutableDictionary<string, string> properties = null, bool displayIfNoReferences = true) { properties ??= ImmutableDictionary<string, string>.Empty; var symbolKey = symbol.GetSymbolKey().ToString(); var projectId = solution.GetOriginatingProjectId(symbol); Contract.ThrowIfNull(projectId); properties = properties.Add(MetadataSymbolKey, symbolKey) .Add(MetadataSymbolOriginatingProjectIdGuid, projectId.Id.ToString()) .Add(MetadataSymbolOriginatingProjectIdDebugName, projectId.DebugName); var originationParts = GetOriginationParts(symbol); return new DefaultDefinitionItem( tags, displayParts, nameDisplayParts, originationParts, sourceSpans: ImmutableArray<DocumentSpan>.Empty, properties: properties, displayableProperties: ImmutableDictionary<string, string>.Empty, displayIfNoReferences: displayIfNoReferences); } // Kept around for binary compat with F#/TypeScript. public static DefinitionItem CreateNonNavigableItem( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<TaggedText> originationParts, bool displayIfNoReferences) { return CreateNonNavigableItem( tags, displayParts, originationParts, properties: null, displayIfNoReferences: displayIfNoReferences); } public static DefinitionItem CreateNonNavigableItem( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<TaggedText> originationParts = default, ImmutableDictionary<string, string> properties = null, bool displayIfNoReferences = true) { properties ??= ImmutableDictionary<string, string>.Empty; properties = properties.Add(NonNavigable, ""); return new DefaultDefinitionItem( tags: tags, displayParts: displayParts, nameDisplayParts: ImmutableArray<TaggedText>.Empty, originationParts: originationParts, sourceSpans: ImmutableArray<DocumentSpan>.Empty, properties: properties, displayableProperties: ImmutableDictionary<string, string>.Empty, displayIfNoReferences: displayIfNoReferences); } internal static ImmutableArray<TaggedText> GetOriginationParts(ISymbol symbol) { // We don't show an origination location for a namespace because it can span over // both metadata assemblies and source projects. // // Otherwise show the assembly this symbol came from as the Origination of // the DefinitionItem. if (symbol.Kind != SymbolKind.Namespace) { var assemblyName = symbol.ContainingAssembly?.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat); if (!string.IsNullOrWhiteSpace(assemblyName)) { return ImmutableArray.Create(new TaggedText(TextTags.Assembly, assemblyName)); } } return ImmutableArray<TaggedText>.Empty; } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.Editor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeRefactorings.MoveType { internal abstract partial class AbstractMoveTypeService<TService, TTypeDeclarationSyntax, TNamespaceDeclarationSyntax, TMemberDeclarationSyntax, TCompilationUnitSyntax> { /// <summary> /// An abstract class for different edits performed by the Move Type Code Action. /// </summary> private abstract class Editor { public Editor( TService service, State state, string fileName, CancellationToken cancellationToken) { State = state; Service = service; FileName = fileName; CancellationToken = cancellationToken; } protected State State { get; } protected TService Service { get; } protected string FileName { get; } protected CancellationToken CancellationToken { get; } protected SemanticDocument SemanticDocument => State.SemanticDocument; /// <summary> /// Operations performed by CodeAction. /// </summary> public virtual async Task<ImmutableArray<CodeActionOperation>> GetOperationsAsync() { var solution = await GetModifiedSolutionAsync().ConfigureAwait(false); if (solution == null) { return ImmutableArray<CodeActionOperation>.Empty; } return ImmutableArray.Create<CodeActionOperation>(new ApplyChangesOperation(solution)); } /// <summary> /// Incremental solution edits that correlate to code operations /// </summary> public abstract Task<Solution> GetModifiedSolutionAsync(); public static Editor GetEditor(MoveTypeOperationKind operationKind, TService service, State state, string fileName, CancellationToken cancellationToken) => operationKind switch { MoveTypeOperationKind.MoveType => new MoveTypeEditor(service, state, fileName, cancellationToken), MoveTypeOperationKind.RenameType => new RenameTypeEditor(service, state, fileName, cancellationToken), MoveTypeOperationKind.RenameFile => new RenameFileEditor(service, state, fileName, cancellationToken), MoveTypeOperationKind.MoveTypeNamespaceScope => new MoveTypeNamespaceScopeEditor(service, state, fileName, cancellationToken), _ => throw ExceptionUtilities.UnexpectedValue(operationKind), }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeRefactorings.MoveType { internal abstract partial class AbstractMoveTypeService<TService, TTypeDeclarationSyntax, TNamespaceDeclarationSyntax, TMemberDeclarationSyntax, TCompilationUnitSyntax> { /// <summary> /// An abstract class for different edits performed by the Move Type Code Action. /// </summary> private abstract class Editor { public Editor( TService service, State state, string fileName, CancellationToken cancellationToken) { State = state; Service = service; FileName = fileName; CancellationToken = cancellationToken; } protected State State { get; } protected TService Service { get; } protected string FileName { get; } protected CancellationToken CancellationToken { get; } protected SemanticDocument SemanticDocument => State.SemanticDocument; /// <summary> /// Operations performed by CodeAction. /// </summary> public virtual async Task<ImmutableArray<CodeActionOperation>> GetOperationsAsync() { var solution = await GetModifiedSolutionAsync().ConfigureAwait(false); if (solution == null) { return ImmutableArray<CodeActionOperation>.Empty; } return ImmutableArray.Create<CodeActionOperation>(new ApplyChangesOperation(solution)); } /// <summary> /// Incremental solution edits that correlate to code operations /// </summary> public abstract Task<Solution> GetModifiedSolutionAsync(); public static Editor GetEditor(MoveTypeOperationKind operationKind, TService service, State state, string fileName, CancellationToken cancellationToken) => operationKind switch { MoveTypeOperationKind.MoveType => new MoveTypeEditor(service, state, fileName, cancellationToken), MoveTypeOperationKind.RenameType => new RenameTypeEditor(service, state, fileName, cancellationToken), MoveTypeOperationKind.RenameFile => new RenameFileEditor(service, state, fileName, cancellationToken), MoveTypeOperationKind.MoveTypeNamespaceScope => new MoveTypeNamespaceScopeEditor(service, state, fileName, cancellationToken), _ => throw ExceptionUtilities.UnexpectedValue(operationKind), }; } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/EncapsulateField/EncapsulateFieldResult.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.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EncapsulateField { internal class EncapsulateFieldResult { public readonly string Name; public readonly Glyph Glyph; private readonly AsyncLazy<Solution> _lazySolution; public EncapsulateFieldResult(string name, Glyph glyph, Func<CancellationToken, Task<Solution>> getSolutionAsync) { Name = name; Glyph = glyph; _lazySolution = new AsyncLazy<Solution>(getSolutionAsync, cacheResult: true); } public Task<Solution> GetSolutionAsync(CancellationToken cancellationToken) => _lazySolution.GetValueAsync(cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EncapsulateField { internal class EncapsulateFieldResult { public readonly string Name; public readonly Glyph Glyph; private readonly AsyncLazy<Solution> _lazySolution; public EncapsulateFieldResult(string name, Glyph glyph, Func<CancellationToken, Task<Solution>> getSolutionAsync) { Name = name; Glyph = glyph; _lazySolution = new AsyncLazy<Solution>(getSolutionAsync, cacheResult: true); } public Task<Solution> GetSolutionAsync(CancellationToken cancellationToken) => _lazySolution.GetValueAsync(cancellationToken); } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Test/Syntax/Parsing/PatternParsingTests.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.Text; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.Patterns)] public class PatternParsingTests : ParsingTests { private new void UsingStatement(string text, params DiagnosticDescription[] expectedErrors) { UsingStatement(text, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8), expectedErrors); } public PatternParsingTests(ITestOutputHelper output) : base(output) { } [Fact] public void CasePatternVersusFeatureFlag() { var test = @" class C { public static void Main(string[] args) { switch ((int) args[0][0]) { case 1: case 2 when args.Length == 2: case 1<<2: case string s: default: break; } bool b = args[0] is string s; } } "; CreateCompilation(test, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)).VerifyDiagnostics( // (9,13): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // case 2 when args.Length == 2: Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "case 2 when args.Length == 2:").WithArguments("pattern matching", "7.0").WithLocation(9, 13), // (11,13): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // case string s: Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "case string s:").WithArguments("pattern matching", "7.0").WithLocation(11, 13), // (15,18): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // bool b = args[0] is string s; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "args[0] is string s").WithArguments("pattern matching", "7.0").WithLocation(15, 18), // (11,18): error CS8121: An expression of type 'int' cannot be handled by a pattern of type 'string'. // case string s: Diagnostic(ErrorCode.ERR_PatternWrongType, "string").WithArguments("int", "string").WithLocation(11, 18), // (11,25): error CS0136: A local or parameter named 's' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case string s: Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "s").WithArguments("s").WithLocation(11, 25) ); } [Fact] public void ThrowExpression_Good() { var test = @"using System; class C { public static void Sample(bool b, string s) { void NeverReturnsFunction() => throw new NullReferenceException(); int x = b ? throw new NullReferenceException() : 1; x = b ? 2 : throw new NullReferenceException(); s = s ?? throw new NullReferenceException(); NeverReturnsFunction(); throw new NullReferenceException() ?? throw new NullReferenceException() ?? throw null; } public static void NeverReturns() => throw new NullReferenceException(); }"; CreateCompilation(test).VerifyDiagnostics(); CreateCompilation(test, parseOptions: TestOptions.Regular6).VerifyDiagnostics( // (6,14): error CS8059: Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater. // void NeverReturnsFunction() => throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "NeverReturnsFunction").WithArguments("local functions", "7.0").WithLocation(6, 14), // (6,40): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // void NeverReturnsFunction() => throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException()").WithArguments("throw expression", "7.0").WithLocation(6, 40), // (7,21): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // int x = b ? throw new NullReferenceException() : 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException()").WithArguments("throw expression", "7.0").WithLocation(7, 21), // (8,21): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // x = b ? 2 : throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException()").WithArguments("throw expression", "7.0").WithLocation(8, 21), // (9,18): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // s = s ?? throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException()").WithArguments("throw expression", "7.0").WithLocation(9, 18), // (11,47): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // throw new NullReferenceException() ?? throw new NullReferenceException() ?? throw null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException() ?? throw null").WithArguments("throw expression", "7.0").WithLocation(11, 47), // (11,85): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // throw new NullReferenceException() ?? throw new NullReferenceException() ?? throw null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw null").WithArguments("throw expression", "7.0").WithLocation(11, 85), // (13,42): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // public static void NeverReturns() => throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException()").WithArguments("throw expression", "7.0").WithLocation(13, 42) ); } [Fact] public void ThrowExpression_Bad() { var test = @"using System; class C { public static void Sample(bool b, string s) { // throw expression at wrong precedence s = s + throw new NullReferenceException(); if (b || throw new NullReferenceException()) { } // throw expression where not permitted var z = from x in throw new NullReferenceException() select x; M(throw new NullReferenceException()); throw throw null; (int, int) w = (1, throw null); return throw null; } static void M(string s) {} }"; CreateCompilationWithMscorlib46(test).VerifyDiagnostics( // (7,17): error CS1525: Invalid expression term 'throw' // s = s + throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "throw new NullReferenceException()").WithArguments("throw").WithLocation(7, 17), // (8,18): error CS1525: Invalid expression term 'throw' // if (b || throw new NullReferenceException()) { } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "throw new NullReferenceException()").WithArguments("throw").WithLocation(8, 18), // (11,27): error CS8115: A throw expression is not allowed in this context. // var z = from x in throw new NullReferenceException() select x; Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(11, 27), // (12,11): error CS8115: A throw expression is not allowed in this context. // M(throw new NullReferenceException()); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(12, 11), // (13,15): error CS8115: A throw expression is not allowed in this context. // throw throw null; Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(13, 15), // (14,9): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // (int, int) w = (1, throw null); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(int, int)").WithArguments("System.ValueTuple`2").WithLocation(14, 9), // (14,28): error CS8115: A throw expression is not allowed in this context. // (int, int) w = (1, throw null); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(14, 28), // (14,24): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // (int, int) w = (1, throw null); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(1, throw null)").WithArguments("System.ValueTuple`2").WithLocation(14, 24), // (15,16): error CS8115: A throw expression is not allowed in this context. // return throw null; Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(15, 16), // (14,9): warning CS0162: Unreachable code detected // (int, int) w = (1, throw null); Diagnostic(ErrorCode.WRN_UnreachableCode, "(").WithLocation(14, 9) ); } [Fact] public void ThrowExpression() { UsingTree(@" class C { int x = y ?? throw null; }", options: TestOptions.Regular); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.CoalesceExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.QuestionQuestionToken); N(SyntaxKind.ThrowExpression); { N(SyntaxKind.ThrowKeyword); N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(14785, "https://github.com/dotnet/roslyn/issues/14785")] public void IsPatternPrecedence_1() { UsingNode(SyntaxFactory.ParseExpression("A is B < C, D > [ ]")); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "B"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } EOF(); } [Fact, WorkItem(14785, "https://github.com/dotnet/roslyn/issues/14785")] public void IsPatternPrecedence_2() { UsingNode(SyntaxFactory.ParseExpression("A < B > C")); N(SyntaxKind.GreaterThanExpression); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.GreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } EOF(); } [Fact, WorkItem(14785, "https://github.com/dotnet/roslyn/issues/14785")] public void IsPatternPrecedence_3() { SyntaxFactory.ParseExpression("e is A<B> && e").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B> || e").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B> ^ e").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B> | e").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B> & e").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B>[]").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("new { X = e is A<B> }").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B>").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("(item is Dictionary<string, object>[])").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("A is B < C, D > [ ]").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("A is B < C, D > [ ] E").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("A < B > C").GetDiagnostics().Verify(); } [Fact] public void QueryContextualPatternVariable_01() { SyntaxFactory.ParseExpression("from s in a where s is string where s.Length > 1 select s").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("M(out int? x)").GetDiagnostics().Verify(); } [Fact] public void TypeDisambiguation_01() { UsingStatement(@" var r = from s in a where s is X<T> // should disambiguate as a type here where M(s) select s as X<T>;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "r"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.QueryExpression); { N(SyntaxKind.FromClause); { N(SyntaxKind.FromKeyword); N(SyntaxKind.IdentifierToken, "s"); N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.QueryBody); { N(SyntaxKind.WhereClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "s"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "X"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } } } N(SyntaxKind.WhereClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "s"); } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SelectClause); { N(SyntaxKind.SelectKeyword); N(SyntaxKind.AsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "s"); } N(SyntaxKind.AsKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "X"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } } } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypeDisambiguation_02() { UsingStatement(@" var r = a is X<T> // should disambiguate as a type here is bool;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "r"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "X"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.IsKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypeDisambiguation_03() { UsingStatement(@" var r = a is X<T> // should disambiguate as a type here > Z;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "r"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.GreaterThanExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "X"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.GreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Z"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence00() { UsingExpression("A is B << C"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence01() { UsingExpression("A is 1 << 2"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence02() { UsingExpression("A is null < B"); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence02b() { UsingExpression("A is B < C"); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence03() { UsingExpression("A is null == B"); N(SyntaxKind.EqualsExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence04() { UsingExpression("A is null & B"); N(SyntaxKind.BitwiseAndExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.AmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence05() { UsingExpression("A is null && B"); N(SyntaxKind.LogicalAndExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.AmpersandAmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence05b() { UsingExpression("A is null || B"); N(SyntaxKind.LogicalOrExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.BarBarToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence06() { UsingStatement(@"switch (e) { case 1 << 2: case B << C: case null < B: case null == B: case null & B: case null && B: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.EqualsExpression); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.BitwiseAndExpression); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.AmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.LogicalAndExpression); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.AmpersandAmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(21515, "https://github.com/dotnet/roslyn/issues/21515")] public void PatternExpressionPrecedence07() { // This should actually be error-free. UsingStatement(@"switch (array) { case KeyValuePair<string, DateTime>[] pairs1: case KeyValuePair<String, DateTime>[] pairs2: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "array"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "KeyValuePair"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "DateTime"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "pairs1"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "KeyValuePair"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "String"); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "DateTime"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "pairs2"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_01() { UsingExpression("A is B***", // (1,10): error CS1733: Expected expression // A is B*** Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(1, 10) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } } } } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_01b() { UsingExpression("A is B*** C"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } } } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_02() { UsingExpression("A is B***[]"); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_03() { UsingExpression("A is B***[] C"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "C"); } } } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_04() { UsingExpression("(B*** C, D)"); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_04b() { UsingExpression("(B*** C)"); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_05() { UsingExpression("(B***[] C, D)"); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "C"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_06() { UsingExpression("(D, B*** C)"); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_07() { UsingExpression("(D, B***[] C)"); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "C"); } } } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_08() { UsingStatement("switch (e) { case B*** C: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_09() { UsingStatement("switch (e) { case B***[] C: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "C"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void NameofInPattern_01() { // This should actually be error-free, because `nameof` might be a type. UsingStatement(@"switch (e) { case nameof n: ; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "nameof"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "n"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void NameofInPattern_02() { // This should actually be error-free; a constant pattern with nameof(n) as the constant. UsingStatement(@"switch (e) { case nameof(n): ; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "nameof"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "n"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void NameofInPattern_03() { // This should actually be error-free; a constant pattern with nameof(n) as the constant. UsingStatement(@"switch (e) { case nameof(n) when true: ; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "nameof"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "n"); } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.WhenClause); { N(SyntaxKind.WhenKeyword); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParenthesizedExpression_01() { UsingStatement(@"switch (e) { case (((3))): ; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParenthesizedExpression_02() { UsingStatement(@"switch (e) { case (((3))) when true: ; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.WhenClause); { N(SyntaxKind.WhenKeyword); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParenthesizedExpression_03() { var expect = new[] { // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case (x: ((3))): ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "(x: ((3)))").WithArguments("recursive patterns", "8.0").WithLocation(1, 19) }; UsingStatement(@"switch (e) { case (x: ((3))): ; }", TestOptions.RegularWithoutRecursivePatterns, expect); checkNodes(); UsingStatement(@"switch (e) { case (x: ((3))): ; }", TestOptions.Regular8); checkNodes(); void checkNodes() { N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } } [Fact] public void ParenthesizedExpression_04() { UsingStatement(@"switch (e) { case (((x: 3))): ; }", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8370: Feature 'parenthesized pattern' is not available in C# 7.3. Please use language version 9.0 or greater. // switch (e) { case (((x: 3))): ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "(((x: 3)))").WithArguments("parenthesized pattern", "9.0").WithLocation(1, 19), // (1,20): error CS8370: Feature 'parenthesized pattern' is not available in C# 7.3. Please use language version 9.0 or greater. // switch (e) { case (((x: 3))): ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "((x: 3))").WithArguments("parenthesized pattern", "9.0").WithLocation(1, 20) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void RecursivePattern_01() { UsingStatement(@"switch (e) { case T(X: 3, Y: 4){L: 5} p: ; }", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case T(X: 3, Y: 4){L: 5} p: ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "T(X: 3, Y: 4){L: 5} p").WithArguments("recursive patterns", "8.0").WithLocation(1, 19) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "L"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "p"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void BrokenPattern_06() { UsingStatement(@"switch (e) { case (: ; }", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case (: ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "(: ").WithArguments("recursive patterns", "8.0").WithLocation(1, 19), // (1,20): error CS1001: Identifier expected // switch (e) { case (: ; } Diagnostic(ErrorCode.ERR_IdentifierExpected, ":").WithLocation(1, 20), // (1,22): error CS1026: ) expected // switch (e) { case (: ; } Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(1, 22), // (1,22): error CS1003: Syntax error, ':' expected // switch (e) { case (: ; } Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(":", ";").WithLocation(1, 22) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void BrokenPattern_07() { UsingStatement(@"switch (e) { case (", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case ( Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "(").WithArguments("recursive patterns", "8.0").WithLocation(1, 19), // (1,20): error CS1026: ) expected // switch (e) { case ( Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(1, 20), // (1,20): error CS1003: Syntax error, ':' expected // switch (e) { case ( Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(":", "").WithLocation(1, 20), // (1,20): error CS1513: } expected // switch (e) { case ( Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(1, 20) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); } } M(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParenthesizedExpression_07() { UsingStatement(@"switch (e) { case (): }", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case (): } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "()").WithArguments("recursive patterns", "8.0").WithLocation(1, 19)); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void BrokenPattern_08() { UsingStatement(@"switch (e) { case", // (1,18): error CS1733: Expected expression // switch (e) { case Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(1, 18), // (1,18): error CS1003: Syntax error, ':' expected // switch (e) { case Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(":", "").WithLocation(1, 18), // (1,18): error CS1513: } expected // switch (e) { case Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(1, 18) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.ColonToken); } } M(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParenthesizedExpression_05() { UsingStatement(@"switch (e) { case (x: ): ; }", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case (x: ): ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "(x: )").WithArguments("recursive patterns", "8.0").WithLocation(1, 19), // (1,23): error CS8504: Pattern missing // switch (e) { case (x: ): ; } Diagnostic(ErrorCode.ERR_MissingPattern, ")").WithLocation(1, 23) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); } M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void EmptySwitchExpression() { UsingExpression("1 switch {}", TestOptions.RegularWithoutRecursivePatterns, // (1,1): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // 1 switch {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1 switch {}").WithArguments("recursive patterns", "8.0").WithLocation(1, 1) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpression01() { UsingExpression("1 switch {a => b, c => d}", TestOptions.RegularWithoutRecursivePatterns, // (1,1): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // 1 switch {a => b, c => d} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1 switch {a => b, c => d}").WithArguments("recursive patterns", "8.0").WithLocation(1, 1) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpression02() { UsingExpression("1 switch { a?b:c => d }", TestOptions.RegularWithoutRecursivePatterns, // (1,1): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // 1 switch { a?b:c => d } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1 switch { a?b:c => d }").WithArguments("recursive patterns", "8.0").WithLocation(1, 1), // (1,13): error CS1003: Syntax error, '=>' expected // 1 switch { a?b:c => d } Diagnostic(ErrorCode.ERR_SyntaxError, "?").WithArguments("=>", "?").WithLocation(1, 13), // (1,13): error CS1525: Invalid expression term '?' // 1 switch { a?b:c => d } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "?").WithArguments("?").WithLocation(1, 13) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } M(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.ConditionalExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleLambdaExpression); { N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpression03() { UsingExpression("1 switch { (a, b, c) => d }", TestOptions.RegularWithoutRecursivePatterns, // (1,1): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // 1 switch { (a, b, c) => d } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1 switch { (a, b, c) => d }").WithArguments("recursive patterns", "8.0").WithLocation(1, 1) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void BrokenRecursivePattern01() { // This put the parser into an infinite loop at one time. The precise diagnostics and nodes // are not as important as the fact that it terminates. UsingStatement("switch (e) { case T( : Q x = n; break; } ", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "T( : Q x = n").WithArguments("recursive patterns", "8.0").WithLocation(1, 19), // (1,22): error CS1001: Identifier expected // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_IdentifierExpected, ":").WithLocation(1, 22), // (1,28): error CS1003: Syntax error, ',' expected // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_SyntaxError, "=").WithArguments(",", "=").WithLocation(1, 28), // (1,30): error CS1003: Syntax error, ',' expected // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_SyntaxError, "n").WithArguments(",", "").WithLocation(1, 30), // (1,31): error CS1026: ) expected // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(1, 31), // (1,31): error CS1003: Syntax error, ':' expected // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(":", ";").WithLocation(1, 31) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Q"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "n"); } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(26000, "https://github.com/dotnet/roslyn/issues/26000")] public void VarIsContextualKeywordForPatterns01() { UsingStatement("switch (e) { case var: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(26000, "https://github.com/dotnet/roslyn/issues/26000")] public void VarIsContextualKeywordForPatterns02() { UsingStatement("if (e is var) {}"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact, WorkItem(26000, "https://github.com/dotnet/roslyn/issues/26000")] public void WhenAsPatternVariable01() { UsingStatement("switch (e) { case var when: break; }", // (1,27): error CS1525: Invalid expression term ':' // switch (e) { case var when: break; } Diagnostic(ErrorCode.ERR_InvalidExprTerm, ":").WithArguments(":").WithLocation(1, 27) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } } N(SyntaxKind.WhenClause); { N(SyntaxKind.WhenKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(26000, "https://github.com/dotnet/roslyn/issues/26000")] public void WhenAsPatternVariable02() { UsingStatement("switch (e) { case K when: break; }", // (1,25): error CS1525: Invalid expression term ':' // switch (e) { case K when: break; } Diagnostic(ErrorCode.ERR_InvalidExprTerm, ":").WithArguments(":").WithLocation(1, 25) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "K"); } } N(SyntaxKind.WhenClause); { N(SyntaxKind.WhenKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact(Skip = "This is not a reliable test, and its failure modes are hard to capture. But it is helpful to run by hand to find parser issues.")] public void ParseFuzz() { Random random = new Random(); for (int i = 0; i < 4000; i++) { string source = $"class C{{void M(){{switch(e){{case {makePattern0()}:T v = e;}}}}}}"; try { Parse(source, options: TestOptions.RegularWithRecursivePatterns); for (int j = 0; j < 30; j++) { int k1 = random.Next(source.Length); int k2 = random.Next(source.Length); string source2 = source.Substring(0, k1) + source.Substring(k2); Parse(source2, options: TestOptions.RegularWithRecursivePatterns); } } catch (StackOverflowException) { Console.WriteLine("Failed on \"" + source + "\""); Assert.True(false, source); } catch (OutOfMemoryException) { Console.WriteLine("Failed on \"" + source + "\""); Assert.True(false, source); } } return; string makeProps(int maxDepth, bool needNames) { int nProps = random.Next(maxDepth); var builder = new StringBuilder(); for (int i = 0; i < nProps; i++) { if (i != 0) builder.Append(", "); if (needNames || random.Next(5) == 0) builder.Append("N: "); builder.Append(makePattern(maxDepth - 1)); } return builder.ToString(); } string makePattern(int maxDepth) { if (maxDepth <= 0 || random.Next(6) == 0) { switch (random.Next(4)) { case 0: return "_"; case 1: return "1"; case 2: return "T x"; default: return "var y"; } } else { // recursive pattern while (true) { bool nameType = random.Next(2) == 0; bool parensPart = random.Next(2) == 0; bool propsPart = random.Next(2) == 0; bool name = random.Next(2) == 0; if (!parensPart && !propsPart && !(nameType && name)) continue; return $"{(nameType ? "N" : "")} {(parensPart ? $"({makeProps(maxDepth, false)})" : "")} {(propsPart ? $"{{ {makeProps(maxDepth, true)} }}" : "")} {(name ? "n" : "")}"; } } } string makePattern0() => makePattern(random.Next(6)); } [Fact] public void ArrayOfTupleType01() { UsingStatement("if (o is (int, int)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType02() { UsingStatement("if (o is (int a, int b)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType03() { UsingStatement("if (o is (int, int)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType04() { UsingStatement("if (o is (int a, int b)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType05() { UsingStatement("if (o is (Int, Int)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType06() { UsingStatement("if (o is (Int a, Int b)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType07() { UsingStatement("if (o is (Int, Int)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType08() { UsingStatement("if (o is (Int a, Int b)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType09() { UsingStatement("if (o is (S.Int, S.Int)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType10() { UsingStatement("if (o is (S.Int a, S.Int b)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType11() { UsingStatement("if (o is (S.Int, S.Int)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType12() { UsingStatement("if (o is (S.Int a, S.Int b)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType13() { UsingStatement("switch (o) { case (int, int)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ArrayOfTupleType14() { UsingStatement("switch (o) { case (int a, int b)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ArrayOfTupleType15() { UsingStatement("switch (o) { case (Int, Int)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ArrayOfTupleType16() { UsingStatement("switch (o) { case (Int a, Int b)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ArrayOfTupleType17() { UsingStatement("switch (o) { case (S.Int, S.Int)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ArrayOfTupleType18() { UsingStatement("switch (o) { case (S.Int a, S.Int b)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void RecursivePattern_00() { UsingStatement("var x = o is Type (Param: 3, Param2: 4) { Prop : 3 } x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_02() { UsingStatement("var x = o is (Param: 3, Param2: 4) { Prop : 3 } x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_03() { UsingStatement("var x = o is Type { Prop : 3 } x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_04() { UsingStatement("var x = o is { Prop : 3 } x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_05() { UsingStatement("var x = o is Type (Param: 3, Param2: 4) x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_06() { UsingStatement("var x = o is (Param: 3, Param2: 4) x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_07() { UsingStatement("var x = o is Type x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_08() { UsingStatement("var x = o is Type (Param: 3, Param2: 4) { Prop : 3 };"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_09() { UsingStatement("var x = o is (Param: 3, Param2: 4) { Prop : 3 };"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_10() { UsingStatement("var x = o is Type { Prop : 3 };"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_11() { UsingStatement("var x = o is { Prop : 3 };"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_12() { UsingStatement("var x = o is Type (Param: 3, Param2: 4);"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_13() { UsingStatement("var x = o is (Param: 3, Param2: 4);"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void ParenthesizedExpressionOfSwitchExpression() { UsingStatement("Console.Write((t) switch {var x => x});"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Console"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Write"); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.SwitchExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "t"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword, "var"); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void DiscardInSwitchExpression() { UsingExpression("e switch { _ => 1 }"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.DiscardPattern); { N(SyntaxKind.UnderscoreToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void DiscardInSwitchStatement_01a() { UsingStatement("switch(e) { case _: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void DiscardInSwitchStatement_01b() { UsingStatement("switch(e) { case _: break; }", TestOptions.Regular7_3); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void DiscardInSwitchStatement_02() { UsingStatement("switch(e) { case _ when true: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } } N(SyntaxKind.WhenClause); { N(SyntaxKind.WhenKeyword); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void DiscardInRecursivePattern_01() { UsingExpression("e is (_, _)"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.DiscardPattern); { N(SyntaxKind.UnderscoreToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.DiscardPattern); { N(SyntaxKind.UnderscoreToken); } } N(SyntaxKind.CloseParenToken); } } } EOF(); } [Fact] public void DiscardInRecursivePattern_02() { UsingExpression("e is { P: _ }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "P"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.DiscardPattern); { N(SyntaxKind.UnderscoreToken); } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void NotDiscardInIsTypeExpression() { UsingExpression("e is _"); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } } EOF(); } [Fact] public void ShortTuplePatterns() { UsingExpression( @"e switch { var () => 1, () => 2, var (x) => 3, (1) _ => 4, (1) x => 5, (1) {} => 6, (Item1: 1) => 7, C(1) => 8 }", expectedErrors: new DiagnosticDescription[0]); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword); N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword); N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "6"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Item1"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "7"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "8"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void NestedShortTuplePatterns() { UsingExpression( @"e switch { {X: var ()} => 1, {X: ()} => 2, {X: var (x)} => 3, {X: (1) _} => 4, {X: (1) x} => 5, {X: (1) {}} => 6, {X: (Item1: 1)} => 7, {X: C(1)} => 8 }", expectedErrors: new DiagnosticDescription[0]); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword); N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword); N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "6"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Item1"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "7"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "8"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void IsNullableArray01() { // OK, this means `(o is A[]) ? b : c` because nullable types are not permitted for a pattern's type UsingExpression("o is A[] ? b : c"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } EOF(); } [Fact] public void IsNullableArray02() { // error: 'cannot use nullable reference type for a pattern' or 'expected :' UsingExpression("o is A[] ? b && c", // (1,18): error CS1003: Syntax error, ':' expected // o is A[] ? b && c Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(":", "").WithLocation(1, 18), // (1,18): error CS1733: Expected expression // o is A[] ? b && c Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(1, 18) ); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.QuestionToken); N(SyntaxKind.LogicalAndExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.AmpersandAmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } EOF(); } [Fact] public void IsNullableArray03() { // OK, this means `(o is A[][]) ? b : c` UsingExpression("o is A[][] ? b : c"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } EOF(); } [Fact] public void IsNullableType01() { UsingExpression("o is A ? b : c"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } EOF(); } [Fact] public void IsNullableType02() { UsingExpression("o is A? ? b : c"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } EOF(); } [Fact, WorkItem(32161, "https://github.com/dotnet/roslyn/issues/32161")] public void ParenthesizedSwitchCase() { var text = @" switch (e) { case (0): break; case (-1): break; case (+2): break; case (~3): break; } "; foreach (var langVersion in new[] { LanguageVersion.CSharp6, LanguageVersion.CSharp7, LanguageVersion.CSharp8 }) { UsingStatement(text, options: CSharpParseOptions.Default.WithLanguageVersion(langVersion)); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.UnaryMinusExpression); { N(SyntaxKind.MinusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.UnaryPlusExpression); { N(SyntaxKind.PlusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.BitwiseNotExpression); { N(SyntaxKind.TildeToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } } [Fact] public void TrailingCommaInSwitchExpression_01() { UsingExpression("1 switch { 1 => 2, }"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void TrailingCommaInSwitchExpression_02() { UsingExpression("1 switch { , }", // (1,12): error CS8504: Pattern missing // 1 switch { , } Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 12), // (1,12): error CS1003: Syntax error, '=>' expected // 1 switch { , } Diagnostic(ErrorCode.ERR_SyntaxError, ",").WithArguments("=>", ",").WithLocation(1, 12), // (1,12): error CS1525: Invalid expression term ',' // 1 switch { , } Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(1, 12) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); M(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.EqualsGreaterThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void TrailingCommaInPropertyPattern_01() { UsingExpression("e is { X: 3, }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void TrailingCommaInPropertyPattern_02() { UsingExpression("e is { , }", // (1,8): error CS8504: Pattern missing // e is { , } Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 8) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); M(SyntaxKind.Subpattern); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void TrailingCommaInPositionalPattern_01() { UsingExpression("e is ( X: 3, )", // (1,14): error CS8504: Pattern missing // e is ( X: 3, ) Diagnostic(ErrorCode.ERR_MissingPattern, ")").WithLocation(1, 14) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.Subpattern); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CloseParenToken); } } } EOF(); } [Fact] public void TrailingCommaInPositionalPattern_02() { UsingExpression("e is ( , )", // (1,8): error CS8504: Pattern missing // e is ( , ) Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 8), // (1,10): error CS8504: Pattern missing // e is ( , ) Diagnostic(ErrorCode.ERR_MissingPattern, ")").WithLocation(1, 10) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.Subpattern); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.Subpattern); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CloseParenToken); } } } EOF(); } [Fact] public void ExtraCommaInSwitchExpression() { UsingExpression("e switch { 1 => 2,, }", // (1,19): error CS8504: Pattern missing // e switch { 1 => 2,, } Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 19), // (1,19): error CS1003: Syntax error, '=>' expected // e switch { 1 => 2,, } Diagnostic(ErrorCode.ERR_SyntaxError, ",").WithArguments("=>", ",").WithLocation(1, 19), // (1,19): error CS1525: Invalid expression term ',' // e switch { 1 => 2,, } Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(1, 19) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); M(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.EqualsGreaterThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ExtraCommaInPropertyPattern() { UsingExpression("e is { A: 1,, }", // (1,13): error CS8504: Pattern missing // e is { A: 1,, } Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 13) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.Subpattern); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact, WorkItem(33054, "https://github.com/dotnet/roslyn/issues/33054")] public void ParenthesizedExpressionInPattern_01() { UsingStatement( @"switch (e) { case (('C') << 24) + (('g') << 16) + (('B') << 8) + 'I': break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.AddExpression); { N(SyntaxKind.AddExpression); { N(SyntaxKind.AddExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "24"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PlusToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "16"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.PlusToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "8"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.PlusToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(33208, "https://github.com/dotnet/roslyn/issues/33208")] public void ParenthesizedExpressionInPattern_02() { UsingStatement( @"switch (e) { case ((2) + (2)): break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PlusToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(33208, "https://github.com/dotnet/roslyn/issues/33208")] public void ParenthesizedExpressionInPattern_03() { UsingStatement( @"switch (e) { case ((2 + 2) - 2): break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SubtractExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.PlusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.MinusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(33208, "https://github.com/dotnet/roslyn/issues/33208")] public void ParenthesizedExpressionInPattern_04() { UsingStatement( @"switch (e) { case (2) | (2): break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.BitwiseOrExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.BarToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(33208, "https://github.com/dotnet/roslyn/issues/33208")] public void ParenthesizedExpressionInPattern_05() { UsingStatement( @"switch (e) { case ((2 << 2) | 2): break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.BitwiseOrExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.BarToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ChainedSwitchExpression_01() { UsingExpression("1 switch { 1 => 2 } switch { 2 => 3 }"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ChainedSwitchExpression_02() { UsingExpression("a < b switch { 1 => 2 } < c switch { 2 => 3 }"); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.LessThanToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void SwitchExpressionPrecedence_01() { UsingExpression("a < b switch { true => 1 }"); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void SwitchExpressionPrecedence_02() { // The left-hand-side of a switch is equality, which binds more loosely than the `switch`, // so `b` ends up on the left of the `switch` and the `a ==` expression has a switch on the right. UsingExpression("a == b switch { true => 1 }"); N(SyntaxKind.EqualsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void SwitchExpressionPrecedence_03() { UsingExpression("a * b switch {}"); N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void SwitchExpressionPrecedence_04() { UsingExpression("a + b switch {}"); N(SyntaxKind.AddExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.PlusToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void SwitchExpressionPrecedence_05() { UsingExpression("-a switch {}"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.UnaryMinusExpression); { N(SyntaxKind.MinusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_06() { UsingExpression("(Type)a switch {}"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_07() { UsingExpression("(Type)a++ switch {}"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.PostIncrementExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.PlusPlusToken); } } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_08() { UsingExpression("+a switch {}"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.UnaryPlusExpression); { N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_09() { UsingExpression("a switch {}.X", // (1,1): error CS1073: Unexpected token '.' // a switch {}.X Diagnostic(ErrorCode.ERR_UnexpectedToken, "a switch {}").WithArguments(".").WithLocation(1, 1)); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_10() { UsingExpression("a switch {}[i]", // (1,1): error CS1073: Unexpected token '[' // a switch {}[i] Diagnostic(ErrorCode.ERR_UnexpectedToken, "a switch {}").WithArguments("[").WithLocation(1, 1)); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_11() { UsingExpression("a switch {}(b)", // (1,1): error CS1073: Unexpected token '(' // a switch {}(b) Diagnostic(ErrorCode.ERR_UnexpectedToken, "a switch {}").WithArguments("(").WithLocation(1, 1)); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_12() { UsingExpression("a switch {}!", // (1,1): error CS1073: Unexpected token '!' // a switch {}! Diagnostic(ErrorCode.ERR_UnexpectedToken, "a switch {}").WithArguments("!").WithLocation(1, 1)); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(32749, "https://github.com/dotnet/roslyn/issues/32749")] public void BrokenSwitchExpression_01() { UsingExpression("(e switch {)", // (1,12): error CS1513: } expected // (e switch {) Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(1, 12) ); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(32749, "https://github.com/dotnet/roslyn/issues/32749")] public void BrokenSwitchExpression_02() { UsingExpression("(e switch {,)", // (1,12): error CS8504: Pattern missing // (e switch {,) Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 12), // (1,12): error CS1003: Syntax error, '=>' expected // (e switch {,) Diagnostic(ErrorCode.ERR_SyntaxError, ",").WithArguments("=>", ",").WithLocation(1, 12), // (1,12): error CS1525: Invalid expression term ',' // (e switch {,) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(1, 12), // (1,13): error CS1513: } expected // (e switch {,) Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(1, 13) ); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); M(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.EqualsGreaterThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(32749, "https://github.com/dotnet/roslyn/issues/32749")] public void BrokenSwitchExpression_03() { UsingExpression("e switch {,", // (1,11): error CS8504: Pattern missing // e switch {, Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 11), // (1,11): error CS1003: Syntax error, '=>' expected // e switch {, Diagnostic(ErrorCode.ERR_SyntaxError, ",").WithArguments("=>", ",").WithLocation(1, 11), // (1,11): error CS1525: Invalid expression term ',' // e switch {, Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(1, 11), // (1,12): error CS1513: } expected // e switch {, Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(1, 12) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); M(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.EqualsGreaterThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); M(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(33675, "https://github.com/dotnet/roslyn/issues/33675")] public void ParenthesizedNamedConstantPatternInSwitchExpression() { UsingExpression("e switch { (X) => 1 }"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(34482, "https://github.com/dotnet/roslyn/issues/34482")] public void SwitchCaseArmErrorRecovery_01() { UsingExpression("e switch { 1 => 1; 2 => 2 }", // (1,18): error CS1003: Syntax error, ',' expected // e switch { 1 => 1; 2 => 2 } Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(",", ";").WithLocation(1, 18) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } M(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(34482, "https://github.com/dotnet/roslyn/issues/34482")] public void SwitchCaseArmErrorRecovery_02() { UsingExpression("e switch { 1 => 1, 2 => 2; }", // (1,26): error CS1003: Syntax error, ',' expected // e switch { 1 => 1, 2 => 2; } Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(",", ";").WithLocation(1, 26) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } M(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(38121, "https://github.com/dotnet/roslyn/issues/38121")] public void GenericPropertyPattern() { UsingExpression("e is A<B> {}"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void PrecedenceInversionWithDeclarationPattern() { UsingExpression("o is C c + d", // (1,10): error CS1073: Unexpected token '+' // o is C c + d Diagnostic(ErrorCode.ERR_UnexpectedToken, "+").WithArguments("+").WithLocation(1, 10) ); N(SyntaxKind.AddExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "c"); } } } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } EOF(); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void PrecedenceInversionWithRecursivePattern() { UsingExpression("o is {} + d", // (1,9): error CS1073: Unexpected token '+' // o is {} + d Diagnostic(ErrorCode.ERR_UnexpectedToken, "+").WithArguments("+").WithLocation(1, 9) ); N(SyntaxKind.AddExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } EOF(); } [Fact] public void PatternCombinators_01() { UsingStatement("_ = e is a or b;", TestOptions.RegularWithoutPatternCombinators, // (1,10): error CS8400: Feature 'or pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = e is a or b; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "a or b").WithArguments("or pattern", "9.0").WithLocation(1, 10) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void PatternCombinators_02() { UsingStatement("_ = e is a and b;", TestOptions.RegularWithoutPatternCombinators, // (1,10): error CS8400: Feature 'and pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = e is a and b; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "a and b").WithArguments("and pattern", "9.0").WithLocation(1, 10) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void PatternCombinators_03() { UsingStatement("_ = e is not b;", TestOptions.RegularWithoutPatternCombinators, // (1,10): error CS8400: Feature 'not pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = e is not b; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "not b").WithArguments("not pattern", "9.0").WithLocation(1, 10) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.NotPattern); { N(SyntaxKind.NotKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void PatternCombinators_04() { UsingStatement("_ = e is not null;", TestOptions.RegularWithoutPatternCombinators, // (1,10): error CS8400: Feature 'not pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = e is not null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "not null").WithArguments("not pattern", "9.0").WithLocation(1, 10) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.NotPattern); { N(SyntaxKind.NotKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void PatternCombinators_05() { UsingStatement( @"_ = e switch { a or b => 1, c and d => 2, not e => 3, not null => 4, };", TestOptions.RegularWithoutPatternCombinators, // (2,5): error CS8400: Feature 'or pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // a or b => 1, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "a or b").WithArguments("or pattern", "9.0").WithLocation(2, 5), // (3,5): error CS8400: Feature 'and pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // c and d => 2, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "c and d").WithArguments("and pattern", "9.0").WithLocation(3, 5), // (4,5): error CS8400: Feature 'not pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // not e => 3, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "not e").WithArguments("not pattern", "9.0").WithLocation(4, 5), // (5,5): error CS8400: Feature 'not pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // not null => 4, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "not null").WithArguments("not pattern", "9.0").WithLocation(5, 5) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.AndPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.NotPattern); { N(SyntaxKind.NotKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.NotPattern); { N(SyntaxKind.NotKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPattern_01() { UsingStatement( @"_ = e switch { < 0 => 0, <= 1 => 1, > 2 => 2, >= 3 => 3, == 4 => 4, != 5 => 5, };", TestOptions.RegularWithoutPatternCombinators, // (2,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // < 0 => 0, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "< 0").WithArguments("relational pattern", "9.0").WithLocation(2, 5), // (3,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // <= 1 => 1, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "<= 1").WithArguments("relational pattern", "9.0").WithLocation(3, 5), // (4,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // > 2 => 2, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "> 2").WithArguments("relational pattern", "9.0").WithLocation(4, 5), // (5,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // >= 3 => 3, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, ">= 3").WithArguments("relational pattern", "9.0").WithLocation(5, 5), // (6,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // == 4 => 4, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "== 4").WithArguments("relational pattern", "9.0").WithLocation(6, 5), // (7,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // != 5 => 5, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "!= 5").WithArguments("relational pattern", "9.0").WithLocation(7, 5) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.ExclamationEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPatternPrecedence_01() { UsingStatement( @"_ = e switch { < 0 < 0 => 0, == 4 < 4 => 4, != 5 < 5 => 5, };", TestOptions.RegularWithPatternCombinators, // (2,9): error CS1003: Syntax error, '=>' expected // < 0 < 0 => 0, Diagnostic(ErrorCode.ERR_SyntaxError, "<").WithArguments("=>", "<").WithLocation(2, 9), // (2,9): error CS1525: Invalid expression term '<' // < 0 < 0 => 0, Diagnostic(ErrorCode.ERR_InvalidExprTerm, "<").WithArguments("<").WithLocation(2, 9), // (2,13): error CS1003: Syntax error, ',' expected // < 0 < 0 => 0, Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(2, 13), // (2,13): error CS8504: Pattern missing // < 0 < 0 => 0, Diagnostic(ErrorCode.ERR_MissingPattern, "=>").WithLocation(2, 13), // (3,10): error CS1003: Syntax error, '=>' expected // == 4 < 4 => 4, Diagnostic(ErrorCode.ERR_SyntaxError, "<").WithArguments("=>", "<").WithLocation(3, 10), // (3,10): error CS1525: Invalid expression term '<' // == 4 < 4 => 4, Diagnostic(ErrorCode.ERR_InvalidExprTerm, "<").WithArguments("<").WithLocation(3, 10), // (3,14): error CS1003: Syntax error, ',' expected // == 4 < 4 => 4, Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(3, 14), // (3,14): error CS8504: Pattern missing // == 4 < 4 => 4, Diagnostic(ErrorCode.ERR_MissingPattern, "=>").WithLocation(3, 14), // (4,10): error CS1003: Syntax error, '=>' expected // != 5 < 5 => 5, Diagnostic(ErrorCode.ERR_SyntaxError, "<").WithArguments("=>", "<").WithLocation(4, 10), // (4,10): error CS1525: Invalid expression term '<' // != 5 < 5 => 5, Diagnostic(ErrorCode.ERR_InvalidExprTerm, "<").WithArguments("<").WithLocation(4, 10), // (4,14): error CS1003: Syntax error, ',' expected // != 5 < 5 => 5, Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(4, 14), // (4,14): error CS8504: Pattern missing // != 5 < 5 => 5, Diagnostic(ErrorCode.ERR_MissingPattern, "=>").WithLocation(4, 14) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } M(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.LessThanExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } M(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.LessThanExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.ExclamationEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } M(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.LessThanExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPatternPrecedence_02() { UsingStatement( @"_ = e switch { < 0 << 0 => 0, == 4 << 4 => 4, != 5 << 5 => 5, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.ExclamationEqualsToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPatternPrecedence_03() { UsingStatement( @"_ = e is < 4;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPatternPrecedence_04() { UsingStatement( @"_ = e is < 4 < 4;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPatternPrecedence_05() { UsingStatement( @"_ = e is < 4 << 4;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void WhenIsNotKeywordInIsExpression() { UsingStatement(@"_ = e is T when;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "when"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void WhenIsNotKeywordInRecursivePattern() { UsingStatement(@"_ = e switch { T(X when) => 1, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "when"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_01() { UsingStatement(@"_ = e is int or long;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.LongKeyword); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_02() { UsingStatement(@"_ = e is int or System.Int64;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int64"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_03() { UsingStatement(@"_ = e switch { int or long => 1, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.OrPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.LongKeyword); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_04() { UsingStatement(@"_ = e switch { int or System.Int64 => 1, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.OrPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int64"); } } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_05() { UsingStatement(@"_ = e switch { T(int) => 1, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_06() { UsingStatement(@"_ = e switch { int => 1, long => 2, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.LongKeyword); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(49354, "https://github.com/dotnet/roslyn/issues/49354")] public void TypePattern_07() { UsingStatement(@"_ = e is (int) or string;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.OrKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_08() { UsingStatement($"_ = e is (a) or b;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CompoundPattern_01() { UsingStatement(@"bool isLetter(char c) => c is >= 'a' and <= 'z' or >= 'A' and <= 'Z';", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.LocalFunctionStatement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } N(SyntaxKind.IdentifierToken, "isLetter"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.CharKeyword); } N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.AndPattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } } N(SyntaxKind.OrKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_01() { UsingStatement(@"_ = e is int and;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "and"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_02() { UsingStatement(@"_ = e is int and < Z;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Z"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_03() { UsingStatement(@"_ = e is int and && b;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.LogicalAndExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "and"); } } } N(SyntaxKind.AmpersandAmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_04() { UsingStatement(@"_ = e is int and int.MaxValue;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "MaxValue"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_05() { UsingStatement(@"_ = e is int and MaxValue;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "MaxValue"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_06() { UsingStatement(@"_ = e is int and ?? Z;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.CoalesceExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "and"); } } } N(SyntaxKind.QuestionQuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Z"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_07() { UsingStatement(@"_ = e is int and ? a : b;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "and"); } } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void PrecedenceInversionWithTypeTest() { UsingExpression("o is int + d", // (1,6): error CS1525: Invalid expression term 'int' // o is int + d Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(1, 6) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.AddExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } } } EOF(); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void PrecedenceInversionWithBlockLambda() { UsingExpression("() => {} + d", // (1,10): warning CS8848: Operator '+' cannot be used here due to precedence. Use parentheses to disambiguate. // () => {} + d Diagnostic(ErrorCode.WRN_PrecedenceInversion, "+").WithArguments("+").WithLocation(1, 10) ); N(SyntaxKind.AddExpression); { N(SyntaxKind.ParenthesizedLambdaExpression); { N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } EOF(); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void PrecedenceInversionWithAnonymousMethod() { UsingExpression("delegate {} + d", // (1,13): warning CS8848: Operator '+' cannot be used here due to precedence. Use parentheses to disambiguate. // delegate {} + d Diagnostic(ErrorCode.WRN_PrecedenceInversion, "+").WithArguments("+").WithLocation(1, 13) ); N(SyntaxKind.AddExpression); { N(SyntaxKind.AnonymousMethodExpression); { N(SyntaxKind.DelegateKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_01() { UsingStatement(@"_ = e is (3);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_02() { UsingStatement(@"_ = e is (A);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_03() { UsingStatement(@"_ = e is (int);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_04() { UsingStatement(@"_ = e is (Item1: int);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Item1"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_05() { UsingStatement(@"_ = e is (A) x;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_06() { UsingStatement(@"_ = e is ((A, A)) x;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void ZeroElementPositional_01() { UsingStatement(@"_ = e is ();", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void ZeroElementPositional_02() { UsingStatement(@"_ = e is () x;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void ZeroElementPositional_03() { UsingStatement(@"_ = e is () {};", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CastExpressionInPattern_01() { UsingStatement(@"_ = e is (int)+1;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.UnaryPlusExpression); { N(SyntaxKind.PlusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Theory] [InlineData("or")] [InlineData("and")] [InlineData("not")] public void CastExpressionInPattern_02(string identifier) { UsingStatement($"_ = e is (int){identifier};", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, identifier); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Theory] [CombinatorialData] public void CastExpressionInPattern_03( [CombinatorialValues("and", "or")] string left, [CombinatorialValues(SyntaxKind.AndKeyword, SyntaxKind.OrKeyword)] SyntaxKind opKind, [CombinatorialValues("and", "or")] string right) { UsingStatement($"_ = e is (int){left} {SyntaxFacts.GetText(opKind)} {right};", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(opKind == SyntaxKind.AndKeyword ? SyntaxKind.AndPattern : SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, left); } } } N(opKind); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, right); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CastExpressionInPattern_04() { UsingStatement($"_ = e is (a)42 or b;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "42"); } } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Theory] [CombinatorialData] public void CombinatorAsConstant_00( [CombinatorialValues("and", "or")] string left, [CombinatorialValues(SyntaxKind.AndKeyword, SyntaxKind.OrKeyword)] SyntaxKind opKind, [CombinatorialValues("and", "or")] string right) { UsingStatement($"_ = e is {left} {SyntaxFacts.GetText(opKind)} {right};", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(opKind == SyntaxKind.AndKeyword ? SyntaxKind.AndPattern : SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, left); } } N(opKind); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, right); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Theory] [CombinatorialData] public void CombinatorAsConstant_01( [CombinatorialValues(SyntaxKind.AndKeyword, SyntaxKind.OrKeyword)] SyntaxKind opKind, [CombinatorialValues("and", "or")] string right) { UsingStatement($"_ = e is (int) {SyntaxFacts.GetText(opKind)} {right};", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(opKind == SyntaxKind.AndKeyword ? SyntaxKind.AndPattern : SyntaxKind.OrPattern); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(opKind); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, right); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsConstant_02() { UsingStatement($"_ = e is (int) or >= 0;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.OrKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsConstant_03() { UsingStatement($"_ = e is (int)or or >= 0;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "or"); } } } N(SyntaxKind.OrKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsConstant_04() { UsingStatement($"_ = e is (int) or or or >= 0;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.OrPattern); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "or"); } } } N(SyntaxKind.OrKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void ConjunctiveFollowedByPropertyPattern_01() { UsingStatement(@"switch (e) { case {} and {}: break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ConjunctiveFollowedByTuplePattern_01() { UsingStatement(@"switch (e) { case {} and (): break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] [WorkItem(42107, "https://github.com/dotnet/roslyn/issues/42107")] public void ParenthesizedRelationalPattern_01() { UsingStatement(@"_ = e is (>= 1);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] [WorkItem(42107, "https://github.com/dotnet/roslyn/issues/42107")] public void ParenthesizedRelationalPattern_02() { UsingStatement(@"_ = e switch { (>= 1) => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] [WorkItem(42107, "https://github.com/dotnet/roslyn/issues/42107")] public void ParenthesizedRelationalPattern_03() { UsingStatement(@"bool isAsciiLetter(char c) => c is (>= 'A' and <= 'Z') or (>= 'a' and <= 'z');", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.LocalFunctionStatement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } N(SyntaxKind.IdentifierToken, "isAsciiLetter"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.CharKeyword); } N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.AndPattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.OrKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.AndPattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] [WorkItem(42107, "https://github.com/dotnet/roslyn/issues/42107")] public void ParenthesizedRelationalPattern_04() { UsingStatement(@"_ = e is (<= 1, >= 2);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void AndPatternAssociativity_01() { UsingStatement(@"_ = e is A and B and C;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.AndPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void OrPatternAssociativity_01() { UsingStatement(@"_ = e is A or B or C;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(43960, "https://github.com/dotnet/roslyn/issues/43960")] public void NamespaceQualifiedEnumConstantInSwitchCase() { var source = @"switch (e) { case global::E.A: break; }"; UsingStatement(source, TestOptions.RegularWithPatternCombinators ); verifyTree(); UsingStatement(source, TestOptions.RegularWithoutPatternCombinators ); verifyTree(); void verifyTree() { N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.GlobalKeyword); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "E"); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } } [Fact, WorkItem(44019, "https://github.com/dotnet/roslyn/issues/44019")] public void NamespaceQualifiedEnumConstantInIsPattern() { var source = @"_ = e is global::E.A;"; UsingStatement(source, TestOptions.RegularWithPatternCombinators ); verifyTree(); UsingStatement(source, TestOptions.RegularWithoutPatternCombinators ); verifyTree(); void verifyTree() { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.GlobalKeyword); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "E"); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact, WorkItem(45757, "https://github.com/dotnet/roslyn/issues/45757")] public void IncompleteTuplePatternInPropertySubpattern() { var source = @"_ = this is Program { P1: (1, }"; var expectedErrors = new[] { // (1,32): error CS1026: ) expected // _ = this is Program { P1: (1, } Diagnostic(ErrorCode.ERR_CloseParenExpected, "}").WithLocation(1, 32), // (1,33): error CS1002: ; expected // _ = this is Program { P1: (1, } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 33) }; UsingStatement(source, TestOptions.RegularWithPatternCombinators, expectedErrors ); verifyTree(); UsingStatement(source, TestOptions.RegularWithoutPatternCombinators, expectedErrors ); verifyTree(); void verifyTree() { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.ThisExpression); { N(SyntaxKind.ThisKeyword); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Program"); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "P1"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } } } M(SyntaxKind.SemicolonToken); } EOF(); } } [Fact, WorkItem(45757, "https://github.com/dotnet/roslyn/issues/45757")] public void IncompleteTuplePattern() { var source = @"_ = i is (1, }"; var expectedErrors = new[] { // (1,1): error CS1073: Unexpected token '}' // _ = i is (1, } Diagnostic(ErrorCode.ERR_UnexpectedToken, "_ = i is (1, ").WithArguments("}").WithLocation(1, 1), // (1,16): error CS1026: ) expected // _ = i is (1, } Diagnostic(ErrorCode.ERR_CloseParenExpected, "}").WithLocation(1, 16), // (1,16): error CS1002: ; expected // _ = i is (1, } Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(1, 16) }; UsingStatement(source, TestOptions.RegularWithPatternCombinators, expectedErrors ); verifyTree(); UsingStatement(source, TestOptions.RegularWithoutPatternCombinators, expectedErrors ); verifyTree(); void verifyTree() { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "i"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.CloseParenToken); } } } } M(SyntaxKind.SemicolonToken); } EOF(); } } [Fact, WorkItem(47614, "https://github.com/dotnet/roslyn/issues/47614")] public void GenericTypeAsTypePatternInSwitchExpression() { UsingStatement(@"_ = e switch { List<X> => 1, List<Y> => 2, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "List"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "List"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchExpression_PredefinedType() { UsingStatement(@"_ = e switch { int? => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchStatement_PredefinedType() { UsingStatement(@"switch(a) { case int?: break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchExpression_PredefinedType_Parenthesized() { UsingStatement(@"_ = e switch { (int?) => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchStatement_PredefinedType_Parenthesized() { UsingStatement(@"switch(a) { case (int?): break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchExpression() { UsingStatement(@"_ = e switch { a? => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchStatement() { UsingStatement(@"switch(a) { case a?: break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchExpression_Parenthesized() { UsingStatement(@"_ = e switch { (a?) => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchStatement_Parenthesized() { UsingStatement(@"switch(a) { case (a?): break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ConditionalAsConstantPatternInSwitchExpression() { UsingStatement(@"_ = e switch { (a?x:y) => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void ConditionalAsConstantPatternInSwitchStatement() { UsingStatement(@"switch(a) { case a?x:y: break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ConditionalAsConstantPatternInSwitchStatement_Parenthesized() { UsingStatement(@"switch(a) { case (a?x:y): break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } } }
// Licensed to the .NET Foundation under one or more 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.Text; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.Patterns)] public class PatternParsingTests : ParsingTests { private new void UsingStatement(string text, params DiagnosticDescription[] expectedErrors) { UsingStatement(text, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8), expectedErrors); } public PatternParsingTests(ITestOutputHelper output) : base(output) { } [Fact] public void CasePatternVersusFeatureFlag() { var test = @" class C { public static void Main(string[] args) { switch ((int) args[0][0]) { case 1: case 2 when args.Length == 2: case 1<<2: case string s: default: break; } bool b = args[0] is string s; } } "; CreateCompilation(test, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)).VerifyDiagnostics( // (9,13): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // case 2 when args.Length == 2: Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "case 2 when args.Length == 2:").WithArguments("pattern matching", "7.0").WithLocation(9, 13), // (11,13): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // case string s: Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "case string s:").WithArguments("pattern matching", "7.0").WithLocation(11, 13), // (15,18): error CS8059: Feature 'pattern matching' is not available in C# 6. Please use language version 7.0 or greater. // bool b = args[0] is string s; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "args[0] is string s").WithArguments("pattern matching", "7.0").WithLocation(15, 18), // (11,18): error CS8121: An expression of type 'int' cannot be handled by a pattern of type 'string'. // case string s: Diagnostic(ErrorCode.ERR_PatternWrongType, "string").WithArguments("int", "string").WithLocation(11, 18), // (11,25): error CS0136: A local or parameter named 's' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // case string s: Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "s").WithArguments("s").WithLocation(11, 25) ); } [Fact] public void ThrowExpression_Good() { var test = @"using System; class C { public static void Sample(bool b, string s) { void NeverReturnsFunction() => throw new NullReferenceException(); int x = b ? throw new NullReferenceException() : 1; x = b ? 2 : throw new NullReferenceException(); s = s ?? throw new NullReferenceException(); NeverReturnsFunction(); throw new NullReferenceException() ?? throw new NullReferenceException() ?? throw null; } public static void NeverReturns() => throw new NullReferenceException(); }"; CreateCompilation(test).VerifyDiagnostics(); CreateCompilation(test, parseOptions: TestOptions.Regular6).VerifyDiagnostics( // (6,14): error CS8059: Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater. // void NeverReturnsFunction() => throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "NeverReturnsFunction").WithArguments("local functions", "7.0").WithLocation(6, 14), // (6,40): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // void NeverReturnsFunction() => throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException()").WithArguments("throw expression", "7.0").WithLocation(6, 40), // (7,21): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // int x = b ? throw new NullReferenceException() : 1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException()").WithArguments("throw expression", "7.0").WithLocation(7, 21), // (8,21): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // x = b ? 2 : throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException()").WithArguments("throw expression", "7.0").WithLocation(8, 21), // (9,18): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // s = s ?? throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException()").WithArguments("throw expression", "7.0").WithLocation(9, 18), // (11,47): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // throw new NullReferenceException() ?? throw new NullReferenceException() ?? throw null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException() ?? throw null").WithArguments("throw expression", "7.0").WithLocation(11, 47), // (11,85): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // throw new NullReferenceException() ?? throw new NullReferenceException() ?? throw null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw null").WithArguments("throw expression", "7.0").WithLocation(11, 85), // (13,42): error CS8059: Feature 'throw expression' is not available in C# 6. Please use language version 7.0 or greater. // public static void NeverReturns() => throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "throw new NullReferenceException()").WithArguments("throw expression", "7.0").WithLocation(13, 42) ); } [Fact] public void ThrowExpression_Bad() { var test = @"using System; class C { public static void Sample(bool b, string s) { // throw expression at wrong precedence s = s + throw new NullReferenceException(); if (b || throw new NullReferenceException()) { } // throw expression where not permitted var z = from x in throw new NullReferenceException() select x; M(throw new NullReferenceException()); throw throw null; (int, int) w = (1, throw null); return throw null; } static void M(string s) {} }"; CreateCompilationWithMscorlib46(test).VerifyDiagnostics( // (7,17): error CS1525: Invalid expression term 'throw' // s = s + throw new NullReferenceException(); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "throw new NullReferenceException()").WithArguments("throw").WithLocation(7, 17), // (8,18): error CS1525: Invalid expression term 'throw' // if (b || throw new NullReferenceException()) { } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "throw new NullReferenceException()").WithArguments("throw").WithLocation(8, 18), // (11,27): error CS8115: A throw expression is not allowed in this context. // var z = from x in throw new NullReferenceException() select x; Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(11, 27), // (12,11): error CS8115: A throw expression is not allowed in this context. // M(throw new NullReferenceException()); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(12, 11), // (13,15): error CS8115: A throw expression is not allowed in this context. // throw throw null; Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(13, 15), // (14,9): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // (int, int) w = (1, throw null); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(int, int)").WithArguments("System.ValueTuple`2").WithLocation(14, 9), // (14,28): error CS8115: A throw expression is not allowed in this context. // (int, int) w = (1, throw null); Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(14, 28), // (14,24): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // (int, int) w = (1, throw null); Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(1, throw null)").WithArguments("System.ValueTuple`2").WithLocation(14, 24), // (15,16): error CS8115: A throw expression is not allowed in this context. // return throw null; Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(15, 16), // (14,9): warning CS0162: Unreachable code detected // (int, int) w = (1, throw null); Diagnostic(ErrorCode.WRN_UnreachableCode, "(").WithLocation(14, 9) ); } [Fact] public void ThrowExpression() { UsingTree(@" class C { int x = y ?? throw null; }", options: TestOptions.Regular); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.CoalesceExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.QuestionQuestionToken); N(SyntaxKind.ThrowExpression); { N(SyntaxKind.ThrowKeyword); N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(14785, "https://github.com/dotnet/roslyn/issues/14785")] public void IsPatternPrecedence_1() { UsingNode(SyntaxFactory.ParseExpression("A is B < C, D > [ ]")); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "B"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } EOF(); } [Fact, WorkItem(14785, "https://github.com/dotnet/roslyn/issues/14785")] public void IsPatternPrecedence_2() { UsingNode(SyntaxFactory.ParseExpression("A < B > C")); N(SyntaxKind.GreaterThanExpression); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.GreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } EOF(); } [Fact, WorkItem(14785, "https://github.com/dotnet/roslyn/issues/14785")] public void IsPatternPrecedence_3() { SyntaxFactory.ParseExpression("e is A<B> && e").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B> || e").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B> ^ e").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B> | e").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B> & e").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B>[]").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("new { X = e is A<B> }").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("e is A<B>").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("(item is Dictionary<string, object>[])").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("A is B < C, D > [ ]").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("A is B < C, D > [ ] E").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("A < B > C").GetDiagnostics().Verify(); } [Fact] public void QueryContextualPatternVariable_01() { SyntaxFactory.ParseExpression("from s in a where s is string where s.Length > 1 select s").GetDiagnostics().Verify(); SyntaxFactory.ParseExpression("M(out int? x)").GetDiagnostics().Verify(); } [Fact] public void TypeDisambiguation_01() { UsingStatement(@" var r = from s in a where s is X<T> // should disambiguate as a type here where M(s) select s as X<T>;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "r"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.QueryExpression); { N(SyntaxKind.FromClause); { N(SyntaxKind.FromKeyword); N(SyntaxKind.IdentifierToken, "s"); N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.QueryBody); { N(SyntaxKind.WhereClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "s"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "X"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } } } N(SyntaxKind.WhereClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "s"); } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SelectClause); { N(SyntaxKind.SelectKeyword); N(SyntaxKind.AsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "s"); } N(SyntaxKind.AsKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "X"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } } } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypeDisambiguation_02() { UsingStatement(@" var r = a is X<T> // should disambiguate as a type here is bool;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "r"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "X"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.IsKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypeDisambiguation_03() { UsingStatement(@" var r = a is X<T> // should disambiguate as a type here > Z;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "r"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.GreaterThanExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "X"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.GreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Z"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence00() { UsingExpression("A is B << C"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence01() { UsingExpression("A is 1 << 2"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence02() { UsingExpression("A is null < B"); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence02b() { UsingExpression("A is B < C"); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence03() { UsingExpression("A is null == B"); N(SyntaxKind.EqualsExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence04() { UsingExpression("A is null & B"); N(SyntaxKind.BitwiseAndExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.AmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence05() { UsingExpression("A is null && B"); N(SyntaxKind.LogicalAndExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.AmpersandAmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence05b() { UsingExpression("A is null || B"); N(SyntaxKind.LogicalOrExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.BarBarToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } EOF(); } [Fact, WorkItem(15734, "https://github.com/dotnet/roslyn/issues/15734")] public void PatternExpressionPrecedence06() { UsingStatement(@"switch (e) { case 1 << 2: case B << C: case null < B: case null == B: case null & B: case null && B: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.EqualsExpression); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.BitwiseAndExpression); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.AmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.LogicalAndExpression); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.AmpersandAmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(21515, "https://github.com/dotnet/roslyn/issues/21515")] public void PatternExpressionPrecedence07() { // This should actually be error-free. UsingStatement(@"switch (array) { case KeyValuePair<string, DateTime>[] pairs1: case KeyValuePair<String, DateTime>[] pairs2: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "array"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "KeyValuePair"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "DateTime"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "pairs1"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "KeyValuePair"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "String"); } N(SyntaxKind.CommaToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "DateTime"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "pairs2"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_01() { UsingExpression("A is B***", // (1,10): error CS1733: Expected expression // A is B*** Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(1, 10) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } } } } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_01b() { UsingExpression("A is B*** C"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } } } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_02() { UsingExpression("A is B***[]"); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_03() { UsingExpression("A is B***[] C"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "C"); } } } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_04() { UsingExpression("(B*** C, D)"); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_04b() { UsingExpression("(B*** C)"); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_05() { UsingExpression("(B***[] C, D)"); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "C"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_06() { UsingExpression("(D, B*** C)"); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_07() { UsingExpression("(D, B***[] C)"); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "D"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "C"); } } } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_08() { UsingStatement("switch (e) { case B*** C: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.PointerIndirectionExpression); { N(SyntaxKind.AsteriskToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(23100, "https://github.com/dotnet/roslyn/issues/23100")] public void ArrayOfPointer_09() { UsingStatement("switch (e) { case B***[] C: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.PointerType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "C"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void NameofInPattern_01() { // This should actually be error-free, because `nameof` might be a type. UsingStatement(@"switch (e) { case nameof n: ; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "nameof"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "n"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void NameofInPattern_02() { // This should actually be error-free; a constant pattern with nameof(n) as the constant. UsingStatement(@"switch (e) { case nameof(n): ; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "nameof"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "n"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void NameofInPattern_03() { // This should actually be error-free; a constant pattern with nameof(n) as the constant. UsingStatement(@"switch (e) { case nameof(n) when true: ; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "nameof"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "n"); } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.WhenClause); { N(SyntaxKind.WhenKeyword); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParenthesizedExpression_01() { UsingStatement(@"switch (e) { case (((3))): ; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParenthesizedExpression_02() { UsingStatement(@"switch (e) { case (((3))) when true: ; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.WhenClause); { N(SyntaxKind.WhenKeyword); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParenthesizedExpression_03() { var expect = new[] { // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case (x: ((3))): ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "(x: ((3)))").WithArguments("recursive patterns", "8.0").WithLocation(1, 19) }; UsingStatement(@"switch (e) { case (x: ((3))): ; }", TestOptions.RegularWithoutRecursivePatterns, expect); checkNodes(); UsingStatement(@"switch (e) { case (x: ((3))): ; }", TestOptions.Regular8); checkNodes(); void checkNodes() { N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } } [Fact] public void ParenthesizedExpression_04() { UsingStatement(@"switch (e) { case (((x: 3))): ; }", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8370: Feature 'parenthesized pattern' is not available in C# 7.3. Please use language version 9.0 or greater. // switch (e) { case (((x: 3))): ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "(((x: 3)))").WithArguments("parenthesized pattern", "9.0").WithLocation(1, 19), // (1,20): error CS8370: Feature 'parenthesized pattern' is not available in C# 7.3. Please use language version 9.0 or greater. // switch (e) { case (((x: 3))): ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "((x: 3))").WithArguments("parenthesized pattern", "9.0").WithLocation(1, 20) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void RecursivePattern_01() { UsingStatement(@"switch (e) { case T(X: 3, Y: 4){L: 5} p: ; }", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case T(X: 3, Y: 4){L: 5} p: ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "T(X: 3, Y: 4){L: 5} p").WithArguments("recursive patterns", "8.0").WithLocation(1, 19) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "L"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "p"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void BrokenPattern_06() { UsingStatement(@"switch (e) { case (: ; }", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case (: ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "(: ").WithArguments("recursive patterns", "8.0").WithLocation(1, 19), // (1,20): error CS1001: Identifier expected // switch (e) { case (: ; } Diagnostic(ErrorCode.ERR_IdentifierExpected, ":").WithLocation(1, 20), // (1,22): error CS1026: ) expected // switch (e) { case (: ; } Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(1, 22), // (1,22): error CS1003: Syntax error, ':' expected // switch (e) { case (: ; } Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(":", ";").WithLocation(1, 22) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void BrokenPattern_07() { UsingStatement(@"switch (e) { case (", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case ( Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "(").WithArguments("recursive patterns", "8.0").WithLocation(1, 19), // (1,20): error CS1026: ) expected // switch (e) { case ( Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(1, 20), // (1,20): error CS1003: Syntax error, ':' expected // switch (e) { case ( Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(":", "").WithLocation(1, 20), // (1,20): error CS1513: } expected // switch (e) { case ( Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(1, 20) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); } } M(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParenthesizedExpression_07() { UsingStatement(@"switch (e) { case (): }", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case (): } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "()").WithArguments("recursive patterns", "8.0").WithLocation(1, 19)); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void BrokenPattern_08() { UsingStatement(@"switch (e) { case", // (1,18): error CS1733: Expected expression // switch (e) { case Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(1, 18), // (1,18): error CS1003: Syntax error, ':' expected // switch (e) { case Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(":", "").WithLocation(1, 18), // (1,18): error CS1513: } expected // switch (e) { case Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(1, 18) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.ColonToken); } } M(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParenthesizedExpression_05() { UsingStatement(@"switch (e) { case (x: ): ; }", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case (x: ): ; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "(x: )").WithArguments("recursive patterns", "8.0").WithLocation(1, 19), // (1,23): error CS8504: Pattern missing // switch (e) { case (x: ): ; } Diagnostic(ErrorCode.ERR_MissingPattern, ")").WithLocation(1, 23) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); } M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void EmptySwitchExpression() { UsingExpression("1 switch {}", TestOptions.RegularWithoutRecursivePatterns, // (1,1): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // 1 switch {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1 switch {}").WithArguments("recursive patterns", "8.0").WithLocation(1, 1) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpression01() { UsingExpression("1 switch {a => b, c => d}", TestOptions.RegularWithoutRecursivePatterns, // (1,1): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // 1 switch {a => b, c => d} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1 switch {a => b, c => d}").WithArguments("recursive patterns", "8.0").WithLocation(1, 1) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpression02() { UsingExpression("1 switch { a?b:c => d }", TestOptions.RegularWithoutRecursivePatterns, // (1,1): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // 1 switch { a?b:c => d } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1 switch { a?b:c => d }").WithArguments("recursive patterns", "8.0").WithLocation(1, 1), // (1,13): error CS1003: Syntax error, '=>' expected // 1 switch { a?b:c => d } Diagnostic(ErrorCode.ERR_SyntaxError, "?").WithArguments("=>", "?").WithLocation(1, 13), // (1,13): error CS1525: Invalid expression term '?' // 1 switch { a?b:c => d } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "?").WithArguments("?").WithLocation(1, 13) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } M(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.ConditionalExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleLambdaExpression); { N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpression03() { UsingExpression("1 switch { (a, b, c) => d }", TestOptions.RegularWithoutRecursivePatterns, // (1,1): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // 1 switch { (a, b, c) => d } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "1 switch { (a, b, c) => d }").WithArguments("recursive patterns", "8.0").WithLocation(1, 1) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void BrokenRecursivePattern01() { // This put the parser into an infinite loop at one time. The precise diagnostics and nodes // are not as important as the fact that it terminates. UsingStatement("switch (e) { case T( : Q x = n; break; } ", TestOptions.RegularWithoutRecursivePatterns, // (1,19): error CS8652: The feature 'recursive patterns' is not available in C# 7.3. Please use language version 8.0 or greater. // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "T( : Q x = n").WithArguments("recursive patterns", "8.0").WithLocation(1, 19), // (1,22): error CS1001: Identifier expected // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_IdentifierExpected, ":").WithLocation(1, 22), // (1,28): error CS1003: Syntax error, ',' expected // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_SyntaxError, "=").WithArguments(",", "=").WithLocation(1, 28), // (1,30): error CS1003: Syntax error, ',' expected // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_SyntaxError, "n").WithArguments(",", "").WithLocation(1, 30), // (1,31): error CS1026: ) expected // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_CloseParenExpected, ";").WithLocation(1, 31), // (1,31): error CS1003: Syntax error, ':' expected // switch (e) { case T( : Q x = n; break; } Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(":", ";").WithLocation(1, 31) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Q"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "n"); } } } M(SyntaxKind.CloseParenToken); } } M(SyntaxKind.ColonToken); } N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(26000, "https://github.com/dotnet/roslyn/issues/26000")] public void VarIsContextualKeywordForPatterns01() { UsingStatement("switch (e) { case var: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(26000, "https://github.com/dotnet/roslyn/issues/26000")] public void VarIsContextualKeywordForPatterns02() { UsingStatement("if (e is var) {}"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact, WorkItem(26000, "https://github.com/dotnet/roslyn/issues/26000")] public void WhenAsPatternVariable01() { UsingStatement("switch (e) { case var when: break; }", // (1,27): error CS1525: Invalid expression term ':' // switch (e) { case var when: break; } Diagnostic(ErrorCode.ERR_InvalidExprTerm, ":").WithArguments(":").WithLocation(1, 27) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } } N(SyntaxKind.WhenClause); { N(SyntaxKind.WhenKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(26000, "https://github.com/dotnet/roslyn/issues/26000")] public void WhenAsPatternVariable02() { UsingStatement("switch (e) { case K when: break; }", // (1,25): error CS1525: Invalid expression term ':' // switch (e) { case K when: break; } Diagnostic(ErrorCode.ERR_InvalidExprTerm, ":").WithArguments(":").WithLocation(1, 25) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "K"); } } N(SyntaxKind.WhenClause); { N(SyntaxKind.WhenKeyword); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact(Skip = "This is not a reliable test, and its failure modes are hard to capture. But it is helpful to run by hand to find parser issues.")] public void ParseFuzz() { Random random = new Random(); for (int i = 0; i < 4000; i++) { string source = $"class C{{void M(){{switch(e){{case {makePattern0()}:T v = e;}}}}}}"; try { Parse(source, options: TestOptions.RegularWithRecursivePatterns); for (int j = 0; j < 30; j++) { int k1 = random.Next(source.Length); int k2 = random.Next(source.Length); string source2 = source.Substring(0, k1) + source.Substring(k2); Parse(source2, options: TestOptions.RegularWithRecursivePatterns); } } catch (StackOverflowException) { Console.WriteLine("Failed on \"" + source + "\""); Assert.True(false, source); } catch (OutOfMemoryException) { Console.WriteLine("Failed on \"" + source + "\""); Assert.True(false, source); } } return; string makeProps(int maxDepth, bool needNames) { int nProps = random.Next(maxDepth); var builder = new StringBuilder(); for (int i = 0; i < nProps; i++) { if (i != 0) builder.Append(", "); if (needNames || random.Next(5) == 0) builder.Append("N: "); builder.Append(makePattern(maxDepth - 1)); } return builder.ToString(); } string makePattern(int maxDepth) { if (maxDepth <= 0 || random.Next(6) == 0) { switch (random.Next(4)) { case 0: return "_"; case 1: return "1"; case 2: return "T x"; default: return "var y"; } } else { // recursive pattern while (true) { bool nameType = random.Next(2) == 0; bool parensPart = random.Next(2) == 0; bool propsPart = random.Next(2) == 0; bool name = random.Next(2) == 0; if (!parensPart && !propsPart && !(nameType && name)) continue; return $"{(nameType ? "N" : "")} {(parensPart ? $"({makeProps(maxDepth, false)})" : "")} {(propsPart ? $"{{ {makeProps(maxDepth, true)} }}" : "")} {(name ? "n" : "")}"; } } } string makePattern0() => makePattern(random.Next(6)); } [Fact] public void ArrayOfTupleType01() { UsingStatement("if (o is (int, int)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType02() { UsingStatement("if (o is (int a, int b)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType03() { UsingStatement("if (o is (int, int)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType04() { UsingStatement("if (o is (int a, int b)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType05() { UsingStatement("if (o is (Int, Int)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType06() { UsingStatement("if (o is (Int a, Int b)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType07() { UsingStatement("if (o is (Int, Int)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType08() { UsingStatement("if (o is (Int a, Int b)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType09() { UsingStatement("if (o is (S.Int, S.Int)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType10() { UsingStatement("if (o is (S.Int a, S.Int b)[]) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType11() { UsingStatement("if (o is (S.Int, S.Int)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType12() { UsingStatement("if (o is (S.Int a, S.Int b)[] q) { }"); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void ArrayOfTupleType13() { UsingStatement("switch (o) { case (int, int)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ArrayOfTupleType14() { UsingStatement("switch (o) { case (int a, int b)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ArrayOfTupleType15() { UsingStatement("switch (o) { case (Int, Int)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ArrayOfTupleType16() { UsingStatement("switch (o) { case (Int a, Int b)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ArrayOfTupleType17() { UsingStatement("switch (o) { case (S.Int, S.Int)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ArrayOfTupleType18() { UsingStatement("switch (o) { case (S.Int a, S.Int b)[] q: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "S"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int"); } } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "q"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void RecursivePattern_00() { UsingStatement("var x = o is Type (Param: 3, Param2: 4) { Prop : 3 } x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_02() { UsingStatement("var x = o is (Param: 3, Param2: 4) { Prop : 3 } x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_03() { UsingStatement("var x = o is Type { Prop : 3 } x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_04() { UsingStatement("var x = o is { Prop : 3 } x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_05() { UsingStatement("var x = o is Type (Param: 3, Param2: 4) x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_06() { UsingStatement("var x = o is (Param: 3, Param2: 4) x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_07() { UsingStatement("var x = o is Type x;"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_08() { UsingStatement("var x = o is Type (Param: 3, Param2: 4) { Prop : 3 };"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_09() { UsingStatement("var x = o is (Param: 3, Param2: 4) { Prop : 3 };"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_10() { UsingStatement("var x = o is Type { Prop : 3 };"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_11() { UsingStatement("var x = o is { Prop : 3 };"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Prop"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CloseBraceToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_12() { UsingStatement("var x = o is Type (Param: 3, Param2: 4);"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RecursivePattern_13() { UsingStatement("var x = o is (Param: 3, Param2: 4);"); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Param2"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.CloseParenToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void ParenthesizedExpressionOfSwitchExpression() { UsingStatement("Console.Write((t) switch {var x => x});"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Console"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Write"); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.SwitchExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "t"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword, "var"); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void DiscardInSwitchExpression() { UsingExpression("e switch { _ => 1 }"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.DiscardPattern); { N(SyntaxKind.UnderscoreToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void DiscardInSwitchStatement_01a() { UsingStatement("switch(e) { case _: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void DiscardInSwitchStatement_01b() { UsingStatement("switch(e) { case _: break; }", TestOptions.Regular7_3); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void DiscardInSwitchStatement_02() { UsingStatement("switch(e) { case _ when true: break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } } N(SyntaxKind.WhenClause); { N(SyntaxKind.WhenKeyword); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void DiscardInRecursivePattern_01() { UsingExpression("e is (_, _)"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.DiscardPattern); { N(SyntaxKind.UnderscoreToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.DiscardPattern); { N(SyntaxKind.UnderscoreToken); } } N(SyntaxKind.CloseParenToken); } } } EOF(); } [Fact] public void DiscardInRecursivePattern_02() { UsingExpression("e is { P: _ }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "P"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.DiscardPattern); { N(SyntaxKind.UnderscoreToken); } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void NotDiscardInIsTypeExpression() { UsingExpression("e is _"); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } } EOF(); } [Fact] public void ShortTuplePatterns() { UsingExpression( @"e switch { var () => 1, () => 2, var (x) => 3, (1) _ => 4, (1) x => 5, (1) {} => 6, (Item1: 1) => 7, C(1) => 8 }", expectedErrors: new DiagnosticDescription[0]); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword); N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword); N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "6"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Item1"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "7"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "8"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void NestedShortTuplePatterns() { UsingExpression( @"e switch { {X: var ()} => 1, {X: ()} => 2, {X: var (x)} => 3, {X: (1) _} => 4, {X: (1) x} => 5, {X: (1) {}} => 6, {X: (Item1: 1)} => 7, {X: C(1)} => 8 }", expectedErrors: new DiagnosticDescription[0]); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword); N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.VarPattern); { N(SyntaxKind.VarKeyword); N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.DiscardDesignation); { N(SyntaxKind.UnderscoreToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "6"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Item1"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "7"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "8"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void IsNullableArray01() { // OK, this means `(o is A[]) ? b : c` because nullable types are not permitted for a pattern's type UsingExpression("o is A[] ? b : c"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } EOF(); } [Fact] public void IsNullableArray02() { // error: 'cannot use nullable reference type for a pattern' or 'expected :' UsingExpression("o is A[] ? b && c", // (1,18): error CS1003: Syntax error, ':' expected // o is A[] ? b && c Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(":", "").WithLocation(1, 18), // (1,18): error CS1733: Expected expression // o is A[] ? b && c Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(1, 18) ); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.QuestionToken); N(SyntaxKind.LogicalAndExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.AmpersandAmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } M(SyntaxKind.ColonToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } EOF(); } [Fact] public void IsNullableArray03() { // OK, this means `(o is A[][]) ? b : c` UsingExpression("o is A[][] ? b : c"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } EOF(); } [Fact] public void IsNullableType01() { UsingExpression("o is A ? b : c"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } EOF(); } [Fact] public void IsNullableType02() { UsingExpression("o is A? ? b : c"); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } EOF(); } [Fact, WorkItem(32161, "https://github.com/dotnet/roslyn/issues/32161")] public void ParenthesizedSwitchCase() { var text = @" switch (e) { case (0): break; case (-1): break; case (+2): break; case (~3): break; } "; foreach (var langVersion in new[] { LanguageVersion.CSharp6, LanguageVersion.CSharp7, LanguageVersion.CSharp8 }) { UsingStatement(text, options: CSharpParseOptions.Default.WithLanguageVersion(langVersion)); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.UnaryMinusExpression); { N(SyntaxKind.MinusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.UnaryPlusExpression); { N(SyntaxKind.PlusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.BitwiseNotExpression); { N(SyntaxKind.TildeToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } } [Fact] public void TrailingCommaInSwitchExpression_01() { UsingExpression("1 switch { 1 => 2, }"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void TrailingCommaInSwitchExpression_02() { UsingExpression("1 switch { , }", // (1,12): error CS8504: Pattern missing // 1 switch { , } Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 12), // (1,12): error CS1003: Syntax error, '=>' expected // 1 switch { , } Diagnostic(ErrorCode.ERR_SyntaxError, ",").WithArguments("=>", ",").WithLocation(1, 12), // (1,12): error CS1525: Invalid expression term ',' // 1 switch { , } Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(1, 12) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); M(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.EqualsGreaterThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void TrailingCommaInPropertyPattern_01() { UsingExpression("e is { X: 3, }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void TrailingCommaInPropertyPattern_02() { UsingExpression("e is { , }", // (1,8): error CS8504: Pattern missing // e is { , } Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 8) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); M(SyntaxKind.Subpattern); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void TrailingCommaInPositionalPattern_01() { UsingExpression("e is ( X: 3, )", // (1,14): error CS8504: Pattern missing // e is ( X: 3, ) Diagnostic(ErrorCode.ERR_MissingPattern, ")").WithLocation(1, 14) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.Subpattern); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CloseParenToken); } } } EOF(); } [Fact] public void TrailingCommaInPositionalPattern_02() { UsingExpression("e is ( , )", // (1,8): error CS8504: Pattern missing // e is ( , ) Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 8), // (1,10): error CS8504: Pattern missing // e is ( , ) Diagnostic(ErrorCode.ERR_MissingPattern, ")").WithLocation(1, 10) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.Subpattern); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.Subpattern); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CloseParenToken); } } } EOF(); } [Fact] public void ExtraCommaInSwitchExpression() { UsingExpression("e switch { 1 => 2,, }", // (1,19): error CS8504: Pattern missing // e switch { 1 => 2,, } Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 19), // (1,19): error CS1003: Syntax error, '=>' expected // e switch { 1 => 2,, } Diagnostic(ErrorCode.ERR_SyntaxError, ",").WithArguments("=>", ",").WithLocation(1, 19), // (1,19): error CS1525: Invalid expression term ',' // e switch { 1 => 2,, } Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(1, 19) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); M(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.EqualsGreaterThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ExtraCommaInPropertyPattern() { UsingExpression("e is { A: 1,, }", // (1,13): error CS8504: Pattern missing // e is { A: 1,, } Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 13) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.Subpattern); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact, WorkItem(33054, "https://github.com/dotnet/roslyn/issues/33054")] public void ParenthesizedExpressionInPattern_01() { UsingStatement( @"switch (e) { case (('C') << 24) + (('g') << 16) + (('B') << 8) + 'I': break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.AddExpression); { N(SyntaxKind.AddExpression); { N(SyntaxKind.AddExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "24"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PlusToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "16"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.PlusToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "8"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.PlusToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(33208, "https://github.com/dotnet/roslyn/issues/33208")] public void ParenthesizedExpressionInPattern_02() { UsingStatement( @"switch (e) { case ((2) + (2)): break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PlusToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(33208, "https://github.com/dotnet/roslyn/issues/33208")] public void ParenthesizedExpressionInPattern_03() { UsingStatement( @"switch (e) { case ((2 + 2) - 2): break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SubtractExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.PlusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.MinusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(33208, "https://github.com/dotnet/roslyn/issues/33208")] public void ParenthesizedExpressionInPattern_04() { UsingStatement( @"switch (e) { case (2) | (2): break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.BitwiseOrExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.BarToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(33208, "https://github.com/dotnet/roslyn/issues/33208")] public void ParenthesizedExpressionInPattern_05() { UsingStatement( @"switch (e) { case ((2 << 2) | 2): break; }"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.BitwiseOrExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.BarToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ChainedSwitchExpression_01() { UsingExpression("1 switch { 1 => 2 } switch { 2 => 3 }"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.SwitchExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ChainedSwitchExpression_02() { UsingExpression("a < b switch { 1 => 2 } < c switch { 2 => 3 }"); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.LessThanToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void SwitchExpressionPrecedence_01() { UsingExpression("a < b switch { true => 1 }"); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.LessThanToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void SwitchExpressionPrecedence_02() { // The left-hand-side of a switch is equality, which binds more loosely than the `switch`, // so `b` ends up on the left of the `switch` and the `a ==` expression has a switch on the right. UsingExpression("a == b switch { true => 1 }"); N(SyntaxKind.EqualsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void SwitchExpressionPrecedence_03() { UsingExpression("a * b switch {}"); N(SyntaxKind.MultiplyExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.AsteriskToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void SwitchExpressionPrecedence_04() { UsingExpression("a + b switch {}"); N(SyntaxKind.AddExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.PlusToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } EOF(); } [Fact] public void SwitchExpressionPrecedence_05() { UsingExpression("-a switch {}"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.UnaryMinusExpression); { N(SyntaxKind.MinusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_06() { UsingExpression("(Type)a switch {}"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_07() { UsingExpression("(Type)a++ switch {}"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Type"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.PostIncrementExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.PlusPlusToken); } } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_08() { UsingExpression("+a switch {}"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.UnaryPlusExpression); { N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_09() { UsingExpression("a switch {}.X", // (1,1): error CS1073: Unexpected token '.' // a switch {}.X Diagnostic(ErrorCode.ERR_UnexpectedToken, "a switch {}").WithArguments(".").WithLocation(1, 1)); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_10() { UsingExpression("a switch {}[i]", // (1,1): error CS1073: Unexpected token '[' // a switch {}[i] Diagnostic(ErrorCode.ERR_UnexpectedToken, "a switch {}").WithArguments("[").WithLocation(1, 1)); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_11() { UsingExpression("a switch {}(b)", // (1,1): error CS1073: Unexpected token '(' // a switch {}(b) Diagnostic(ErrorCode.ERR_UnexpectedToken, "a switch {}").WithArguments("(").WithLocation(1, 1)); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void SwitchExpressionPrecedence_12() { UsingExpression("a switch {}!", // (1,1): error CS1073: Unexpected token '!' // a switch {}! Diagnostic(ErrorCode.ERR_UnexpectedToken, "a switch {}").WithArguments("!").WithLocation(1, 1)); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(32749, "https://github.com/dotnet/roslyn/issues/32749")] public void BrokenSwitchExpression_01() { UsingExpression("(e switch {)", // (1,12): error CS1513: } expected // (e switch {) Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(1, 12) ); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(32749, "https://github.com/dotnet/roslyn/issues/32749")] public void BrokenSwitchExpression_02() { UsingExpression("(e switch {,)", // (1,12): error CS8504: Pattern missing // (e switch {,) Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 12), // (1,12): error CS1003: Syntax error, '=>' expected // (e switch {,) Diagnostic(ErrorCode.ERR_SyntaxError, ",").WithArguments("=>", ",").WithLocation(1, 12), // (1,12): error CS1525: Invalid expression term ',' // (e switch {,) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(1, 12), // (1,13): error CS1513: } expected // (e switch {,) Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(1, 13) ); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); M(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.EqualsGreaterThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CloseParenToken); } EOF(); } [Fact, WorkItem(32749, "https://github.com/dotnet/roslyn/issues/32749")] public void BrokenSwitchExpression_03() { UsingExpression("e switch {,", // (1,11): error CS8504: Pattern missing // e switch {, Diagnostic(ErrorCode.ERR_MissingPattern, ",").WithLocation(1, 11), // (1,11): error CS1003: Syntax error, '=>' expected // e switch {, Diagnostic(ErrorCode.ERR_SyntaxError, ",").WithArguments("=>", ",").WithLocation(1, 11), // (1,11): error CS1525: Invalid expression term ',' // e switch {, Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(1, 11), // (1,12): error CS1513: } expected // e switch {, Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(1, 12) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); M(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.EqualsGreaterThanToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CommaToken); M(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(33675, "https://github.com/dotnet/roslyn/issues/33675")] public void ParenthesizedNamedConstantPatternInSwitchExpression() { UsingExpression("e switch { (X) => 1 }"); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(34482, "https://github.com/dotnet/roslyn/issues/34482")] public void SwitchCaseArmErrorRecovery_01() { UsingExpression("e switch { 1 => 1; 2 => 2 }", // (1,18): error CS1003: Syntax error, ',' expected // e switch { 1 => 1; 2 => 2 } Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(",", ";").WithLocation(1, 18) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } M(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(34482, "https://github.com/dotnet/roslyn/issues/34482")] public void SwitchCaseArmErrorRecovery_02() { UsingExpression("e switch { 1 => 1, 2 => 2; }", // (1,26): error CS1003: Syntax error, ',' expected // e switch { 1 => 1, 2 => 2; } Diagnostic(ErrorCode.ERR_SyntaxError, ";").WithArguments(",", ";").WithLocation(1, 26) ); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } M(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(38121, "https://github.com/dotnet/roslyn/issues/38121")] public void GenericPropertyPattern() { UsingExpression("e is A<B> {}"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void PrecedenceInversionWithDeclarationPattern() { UsingExpression("o is C c + d", // (1,10): error CS1073: Unexpected token '+' // o is C c + d Diagnostic(ErrorCode.ERR_UnexpectedToken, "+").WithArguments("+").WithLocation(1, 10) ); N(SyntaxKind.AddExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "c"); } } } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } EOF(); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void PrecedenceInversionWithRecursivePattern() { UsingExpression("o is {} + d", // (1,9): error CS1073: Unexpected token '+' // o is {} + d Diagnostic(ErrorCode.ERR_UnexpectedToken, "+").WithArguments("+").WithLocation(1, 9) ); N(SyntaxKind.AddExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } EOF(); } [Fact] public void PatternCombinators_01() { UsingStatement("_ = e is a or b;", TestOptions.RegularWithoutPatternCombinators, // (1,10): error CS8400: Feature 'or pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = e is a or b; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "a or b").WithArguments("or pattern", "9.0").WithLocation(1, 10) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void PatternCombinators_02() { UsingStatement("_ = e is a and b;", TestOptions.RegularWithoutPatternCombinators, // (1,10): error CS8400: Feature 'and pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = e is a and b; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "a and b").WithArguments("and pattern", "9.0").WithLocation(1, 10) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void PatternCombinators_03() { UsingStatement("_ = e is not b;", TestOptions.RegularWithoutPatternCombinators, // (1,10): error CS8400: Feature 'not pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = e is not b; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "not b").WithArguments("not pattern", "9.0").WithLocation(1, 10) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.NotPattern); { N(SyntaxKind.NotKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void PatternCombinators_04() { UsingStatement("_ = e is not null;", TestOptions.RegularWithoutPatternCombinators, // (1,10): error CS8400: Feature 'not pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // _ = e is not null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "not null").WithArguments("not pattern", "9.0").WithLocation(1, 10) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.NotPattern); { N(SyntaxKind.NotKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void PatternCombinators_05() { UsingStatement( @"_ = e switch { a or b => 1, c and d => 2, not e => 3, not null => 4, };", TestOptions.RegularWithoutPatternCombinators, // (2,5): error CS8400: Feature 'or pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // a or b => 1, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "a or b").WithArguments("or pattern", "9.0").WithLocation(2, 5), // (3,5): error CS8400: Feature 'and pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // c and d => 2, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "c and d").WithArguments("and pattern", "9.0").WithLocation(3, 5), // (4,5): error CS8400: Feature 'not pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // not e => 3, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "not e").WithArguments("not pattern", "9.0").WithLocation(4, 5), // (5,5): error CS8400: Feature 'not pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // not null => 4, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "not null").WithArguments("not pattern", "9.0").WithLocation(5, 5) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.AndPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.NotPattern); { N(SyntaxKind.NotKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.NotPattern); { N(SyntaxKind.NotKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPattern_01() { UsingStatement( @"_ = e switch { < 0 => 0, <= 1 => 1, > 2 => 2, >= 3 => 3, == 4 => 4, != 5 => 5, };", TestOptions.RegularWithoutPatternCombinators, // (2,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // < 0 => 0, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "< 0").WithArguments("relational pattern", "9.0").WithLocation(2, 5), // (3,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // <= 1 => 1, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "<= 1").WithArguments("relational pattern", "9.0").WithLocation(3, 5), // (4,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // > 2 => 2, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "> 2").WithArguments("relational pattern", "9.0").WithLocation(4, 5), // (5,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // >= 3 => 3, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, ">= 3").WithArguments("relational pattern", "9.0").WithLocation(5, 5), // (6,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // == 4 => 4, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "== 4").WithArguments("relational pattern", "9.0").WithLocation(6, 5), // (7,5): error CS8400: Feature 'relational pattern' is not available in C# 8.0. Please use language version 9.0 or greater. // != 5 => 5, Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "!= 5").WithArguments("relational pattern", "9.0").WithLocation(7, 5) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.ExclamationEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPatternPrecedence_01() { UsingStatement( @"_ = e switch { < 0 < 0 => 0, == 4 < 4 => 4, != 5 < 5 => 5, };", TestOptions.RegularWithPatternCombinators, // (2,9): error CS1003: Syntax error, '=>' expected // < 0 < 0 => 0, Diagnostic(ErrorCode.ERR_SyntaxError, "<").WithArguments("=>", "<").WithLocation(2, 9), // (2,9): error CS1525: Invalid expression term '<' // < 0 < 0 => 0, Diagnostic(ErrorCode.ERR_InvalidExprTerm, "<").WithArguments("<").WithLocation(2, 9), // (2,13): error CS1003: Syntax error, ',' expected // < 0 < 0 => 0, Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(2, 13), // (2,13): error CS8504: Pattern missing // < 0 < 0 => 0, Diagnostic(ErrorCode.ERR_MissingPattern, "=>").WithLocation(2, 13), // (3,10): error CS1003: Syntax error, '=>' expected // == 4 < 4 => 4, Diagnostic(ErrorCode.ERR_SyntaxError, "<").WithArguments("=>", "<").WithLocation(3, 10), // (3,10): error CS1525: Invalid expression term '<' // == 4 < 4 => 4, Diagnostic(ErrorCode.ERR_InvalidExprTerm, "<").WithArguments("<").WithLocation(3, 10), // (3,14): error CS1003: Syntax error, ',' expected // == 4 < 4 => 4, Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(3, 14), // (3,14): error CS8504: Pattern missing // == 4 < 4 => 4, Diagnostic(ErrorCode.ERR_MissingPattern, "=>").WithLocation(3, 14), // (4,10): error CS1003: Syntax error, '=>' expected // != 5 < 5 => 5, Diagnostic(ErrorCode.ERR_SyntaxError, "<").WithArguments("=>", "<").WithLocation(4, 10), // (4,10): error CS1525: Invalid expression term '<' // != 5 < 5 => 5, Diagnostic(ErrorCode.ERR_InvalidExprTerm, "<").WithArguments("<").WithLocation(4, 10), // (4,14): error CS1003: Syntax error, ',' expected // != 5 < 5 => 5, Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(",", "=>").WithLocation(4, 14), // (4,14): error CS8504: Pattern missing // != 5 < 5 => 5, Diagnostic(ErrorCode.ERR_MissingPattern, "=>").WithLocation(4, 14) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } M(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.LessThanExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } M(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.LessThanExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.ExclamationEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } M(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.LessThanExpression); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { M(SyntaxKind.ConstantPattern); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPatternPrecedence_02() { UsingStatement( @"_ = e switch { < 0 << 0 => 0, == 4 << 4 => 4, != 5 << 5 => 5, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.EqualsEqualsToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.ExclamationEqualsToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "5"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPatternPrecedence_03() { UsingStatement( @"_ = e is < 4;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPatternPrecedence_04() { UsingStatement( @"_ = e is < 4 < 4;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.LessThanExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.LessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void RelationalPatternPrecedence_05() { UsingStatement( @"_ = e is < 4 << 4;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.LeftShiftExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } N(SyntaxKind.LessThanLessThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void WhenIsNotKeywordInIsExpression() { UsingStatement(@"_ = e is T when;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "when"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void WhenIsNotKeywordInRecursivePattern() { UsingStatement(@"_ = e switch { T(X when) => 1, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "when"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_01() { UsingStatement(@"_ = e is int or long;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.LongKeyword); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_02() { UsingStatement(@"_ = e is int or System.Int64;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int64"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_03() { UsingStatement(@"_ = e switch { int or long => 1, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.OrPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.LongKeyword); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_04() { UsingStatement(@"_ = e switch { int or System.Int64 => 1, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.OrPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int64"); } } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_05() { UsingStatement(@"_ = e switch { T(int) => 1, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_06() { UsingStatement(@"_ = e switch { int => 1, long => 2, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.LongKeyword); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(49354, "https://github.com/dotnet/roslyn/issues/49354")] public void TypePattern_07() { UsingStatement(@"_ = e is (int) or string;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.OrKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TypePattern_08() { UsingStatement($"_ = e is (a) or b;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CompoundPattern_01() { UsingStatement(@"bool isLetter(char c) => c is >= 'a' and <= 'z' or >= 'A' and <= 'Z';", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.LocalFunctionStatement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } N(SyntaxKind.IdentifierToken, "isLetter"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.CharKeyword); } N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.AndPattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } } N(SyntaxKind.OrKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_01() { UsingStatement(@"_ = e is int and;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "and"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_02() { UsingStatement(@"_ = e is int and < Z;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Z"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_03() { UsingStatement(@"_ = e is int and && b;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.LogicalAndExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "and"); } } } N(SyntaxKind.AmpersandAmpersandToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_04() { UsingStatement(@"_ = e is int and int.MaxValue;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "MaxValue"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_05() { UsingStatement(@"_ = e is int and MaxValue;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "MaxValue"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_06() { UsingStatement(@"_ = e is int and ?? Z;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.CoalesceExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "and"); } } } N(SyntaxKind.QuestionQuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Z"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsDesignator_07() { UsingStatement(@"_ = e is int and ? a : b;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.DeclarationPattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "and"); } } } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void PrecedenceInversionWithTypeTest() { UsingExpression("o is int + d", // (1,6): error CS1525: Invalid expression term 'int' // o is int + d Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(1, 6) ); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "o"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.AddExpression); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } } } EOF(); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void PrecedenceInversionWithBlockLambda() { UsingExpression("() => {} + d", // (1,10): warning CS8848: Operator '+' cannot be used here due to precedence. Use parentheses to disambiguate. // () => {} + d Diagnostic(ErrorCode.WRN_PrecedenceInversion, "+").WithArguments("+").WithLocation(1, 10) ); N(SyntaxKind.AddExpression); { N(SyntaxKind.ParenthesizedLambdaExpression); { N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } EOF(); } [Fact, WorkItem(10492, "https://github.com/dotnet/roslyn/issues/10492")] public void PrecedenceInversionWithAnonymousMethod() { UsingExpression("delegate {} + d", // (1,13): warning CS8848: Operator '+' cannot be used here due to precedence. Use parentheses to disambiguate. // delegate {} + d Diagnostic(ErrorCode.WRN_PrecedenceInversion, "+").WithArguments("+").WithLocation(1, 13) ); N(SyntaxKind.AddExpression); { N(SyntaxKind.AnonymousMethodExpression); { N(SyntaxKind.DelegateKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_01() { UsingStatement(@"_ = e is (3);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "3"); } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_02() { UsingStatement(@"_ = e is (A);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_03() { UsingStatement(@"_ = e is (int);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_04() { UsingStatement(@"_ = e is (Item1: int);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Item1"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_05() { UsingStatement(@"_ = e is (A) x;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void OneElementPositional_06() { UsingStatement(@"_ = e is ((A, A)) x;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void ZeroElementPositional_01() { UsingStatement(@"_ = e is ();", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void ZeroElementPositional_02() { UsingStatement(@"_ = e is () x;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(36515, "https://github.com/dotnet/roslyn/issues/36515")] public void ZeroElementPositional_03() { UsingStatement(@"_ = e is () {};", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CastExpressionInPattern_01() { UsingStatement(@"_ = e is (int)+1;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.UnaryPlusExpression); { N(SyntaxKind.PlusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Theory] [InlineData("or")] [InlineData("and")] [InlineData("not")] public void CastExpressionInPattern_02(string identifier) { UsingStatement($"_ = e is (int){identifier};", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, identifier); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Theory] [CombinatorialData] public void CastExpressionInPattern_03( [CombinatorialValues("and", "or")] string left, [CombinatorialValues(SyntaxKind.AndKeyword, SyntaxKind.OrKeyword)] SyntaxKind opKind, [CombinatorialValues("and", "or")] string right) { UsingStatement($"_ = e is (int){left} {SyntaxFacts.GetText(opKind)} {right};", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(opKind == SyntaxKind.AndKeyword ? SyntaxKind.AndPattern : SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, left); } } } N(opKind); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, right); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CastExpressionInPattern_04() { UsingStatement($"_ = e is (a)42 or b;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "42"); } } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Theory] [CombinatorialData] public void CombinatorAsConstant_00( [CombinatorialValues("and", "or")] string left, [CombinatorialValues(SyntaxKind.AndKeyword, SyntaxKind.OrKeyword)] SyntaxKind opKind, [CombinatorialValues("and", "or")] string right) { UsingStatement($"_ = e is {left} {SyntaxFacts.GetText(opKind)} {right};", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(opKind == SyntaxKind.AndKeyword ? SyntaxKind.AndPattern : SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, left); } } N(opKind); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, right); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Theory] [CombinatorialData] public void CombinatorAsConstant_01( [CombinatorialValues(SyntaxKind.AndKeyword, SyntaxKind.OrKeyword)] SyntaxKind opKind, [CombinatorialValues("and", "or")] string right) { UsingStatement($"_ = e is (int) {SyntaxFacts.GetText(opKind)} {right};", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(opKind == SyntaxKind.AndKeyword ? SyntaxKind.AndPattern : SyntaxKind.OrPattern); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(opKind); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, right); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsConstant_02() { UsingStatement($"_ = e is (int) or >= 0;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.OrKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsConstant_03() { UsingStatement($"_ = e is (int)or or >= 0;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "or"); } } } N(SyntaxKind.OrKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void CombinatorAsConstant_04() { UsingStatement($"_ = e is (int) or or or >= 0;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.OrPattern); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "or"); } } } N(SyntaxKind.OrKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void ConjunctiveFollowedByPropertyPattern_01() { UsingStatement(@"switch (e) { case {} and {}: break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ConjunctiveFollowedByTuplePattern_01() { UsingStatement(@"switch (e) { case {} and (): break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] [WorkItem(42107, "https://github.com/dotnet/roslyn/issues/42107")] public void ParenthesizedRelationalPattern_01() { UsingStatement(@"_ = e is (>= 1);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] [WorkItem(42107, "https://github.com/dotnet/roslyn/issues/42107")] public void ParenthesizedRelationalPattern_02() { UsingStatement(@"_ = e switch { (>= 1) => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] [WorkItem(42107, "https://github.com/dotnet/roslyn/issues/42107")] public void ParenthesizedRelationalPattern_03() { UsingStatement(@"bool isAsciiLetter(char c) => c is (>= 'A' and <= 'Z') or (>= 'a' and <= 'z');", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.LocalFunctionStatement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.BoolKeyword); } N(SyntaxKind.IdentifierToken, "isAsciiLetter"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.CharKeyword); } N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.AndPattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.OrKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.AndPattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.CharacterLiteralExpression); { N(SyntaxKind.CharacterLiteralToken); } } } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] [WorkItem(42107, "https://github.com/dotnet/roslyn/issues/42107")] public void ParenthesizedRelationalPattern_04() { UsingStatement(@"_ = e is (<= 1, >= 2);", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.LessThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } } N(SyntaxKind.CloseParenToken); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void AndPatternAssociativity_01() { UsingStatement(@"_ = e is A and B and C;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.AndPattern); { N(SyntaxKind.AndPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } } N(SyntaxKind.AndKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void OrPatternAssociativity_01() { UsingStatement(@"_ = e is A or B or C;", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.OrPattern); { N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(43960, "https://github.com/dotnet/roslyn/issues/43960")] public void NamespaceQualifiedEnumConstantInSwitchCase() { var source = @"switch (e) { case global::E.A: break; }"; UsingStatement(source, TestOptions.RegularWithPatternCombinators ); verifyTree(); UsingStatement(source, TestOptions.RegularWithoutPatternCombinators ); verifyTree(); void verifyTree() { N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.GlobalKeyword); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "E"); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } } [Fact, WorkItem(44019, "https://github.com/dotnet/roslyn/issues/44019")] public void NamespaceQualifiedEnumConstantInIsPattern() { var source = @"_ = e is global::E.A;"; UsingStatement(source, TestOptions.RegularWithPatternCombinators ); verifyTree(); UsingStatement(source, TestOptions.RegularWithoutPatternCombinators ); verifyTree(); void verifyTree() { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.AliasQualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.GlobalKeyword); } N(SyntaxKind.ColonColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "E"); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } } } N(SyntaxKind.SemicolonToken); } EOF(); } } [Fact, WorkItem(45757, "https://github.com/dotnet/roslyn/issues/45757")] public void IncompleteTuplePatternInPropertySubpattern() { var source = @"_ = this is Program { P1: (1, }"; var expectedErrors = new[] { // (1,32): error CS1026: ) expected // _ = this is Program { P1: (1, } Diagnostic(ErrorCode.ERR_CloseParenExpected, "}").WithLocation(1, 32), // (1,33): error CS1002: ; expected // _ = this is Program { P1: (1, } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 33) }; UsingStatement(source, TestOptions.RegularWithPatternCombinators, expectedErrors ); verifyTree(); UsingStatement(source, TestOptions.RegularWithoutPatternCombinators, expectedErrors ); verifyTree(); void verifyTree() { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.ThisExpression); { N(SyntaxKind.ThisKeyword); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Program"); } N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "P1"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.CloseBraceToken); } } } } M(SyntaxKind.SemicolonToken); } EOF(); } } [Fact, WorkItem(45757, "https://github.com/dotnet/roslyn/issues/45757")] public void IncompleteTuplePattern() { var source = @"_ = i is (1, }"; var expectedErrors = new[] { // (1,1): error CS1073: Unexpected token '}' // _ = i is (1, } Diagnostic(ErrorCode.ERR_UnexpectedToken, "_ = i is (1, ").WithArguments("}").WithLocation(1, 1), // (1,16): error CS1026: ) expected // _ = i is (1, } Diagnostic(ErrorCode.ERR_CloseParenExpected, "}").WithLocation(1, 16), // (1,16): error CS1002: ; expected // _ = i is (1, } Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(1, 16) }; UsingStatement(source, TestOptions.RegularWithPatternCombinators, expectedErrors ); verifyTree(); UsingStatement(source, TestOptions.RegularWithoutPatternCombinators, expectedErrors ); verifyTree(); void verifyTree() { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "i"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } N(SyntaxKind.CommaToken); M(SyntaxKind.CloseParenToken); } } } } M(SyntaxKind.SemicolonToken); } EOF(); } } [Fact, WorkItem(47614, "https://github.com/dotnet/roslyn/issues/47614")] public void GenericTypeAsTypePatternInSwitchExpression() { UsingStatement(@"_ = e switch { List<X> => 1, List<Y> => 2, };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "List"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "List"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.GreaterThanToken); } } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchExpression_PredefinedType() { UsingStatement(@"_ = e switch { int? => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchStatement_PredefinedType() { UsingStatement(@"switch(a) { case int?: break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchExpression_PredefinedType_Parenthesized() { UsingStatement(@"_ = e switch { (int?) => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchStatement_PredefinedType_Parenthesized() { UsingStatement(@"switch(a) { case (int?): break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchExpression() { UsingStatement(@"_ = e switch { a? => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchStatement() { UsingStatement(@"switch(a) { case a?: break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchExpression_Parenthesized() { UsingStatement(@"_ = e switch { (a?) => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact, WorkItem(48112, "https://github.com/dotnet/roslyn/issues/48112")] public void NullableTypeAsTypePatternInSwitchStatement_Parenthesized() { UsingStatement(@"switch(a) { case (a?): break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CasePatternSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedPattern); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TypePattern); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ConditionalAsConstantPatternInSwitchExpression() { UsingStatement(@"_ = e switch { (a?x:y) => 1 };", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchExpressionArm); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void ConditionalAsConstantPatternInSwitchStatement() { UsingStatement(@"switch(a) { case a?x:y: break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ConditionalAsConstantPatternInSwitchStatement_Parenthesized() { UsingStatement(@"switch(a) { case (a?x:y): break; }", TestOptions.RegularWithPatternCombinators ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.CaseSwitchLabel); { N(SyntaxKind.CaseKeyword); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.BreakStatement); { N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } EOF(); } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Dependencies/Collections/Internal/SegmentedArraySegment`1.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.Collections.Internal { internal readonly struct SegmentedArraySegment<T> { public SegmentedArray<T> Array { get; } public int Start { get; } public int Length { get; } public SegmentedArraySegment(SegmentedArray<T> array, int start, int length) { Array = array; Start = start; Length = length; } public ref T this[int index] { get { if ((uint)index >= (uint)Length) ThrowHelper.ThrowIndexOutOfRangeException(); return ref Array[index + Start]; } } public SegmentedArraySegment<T> Slice(int start) { if ((uint)start >= (uint)Length) ThrowHelper.ThrowArgumentOutOfRangeException(); return new SegmentedArraySegment<T>(Array, Start + start, Length - start); } public SegmentedArraySegment<T> Slice(int start, int length) { // Since start and length are both 32-bit, their sum can be computed across a 64-bit domain // without loss of fidelity. The cast to uint before the cast to ulong ensures that the // extension from 32- to 64-bit is zero-extending rather than sign-extending. The end result // of this is that if either input is negative or if the input sum overflows past Int32.MaxValue, // that information is captured correctly in the comparison against the backing _length field. if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)Length) ThrowHelper.ThrowArgumentOutOfRangeException(); return new SegmentedArraySegment<T>(Array, Start + start, 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. namespace Microsoft.CodeAnalysis.Collections.Internal { internal readonly struct SegmentedArraySegment<T> { public SegmentedArray<T> Array { get; } public int Start { get; } public int Length { get; } public SegmentedArraySegment(SegmentedArray<T> array, int start, int length) { Array = array; Start = start; Length = length; } public ref T this[int index] { get { if ((uint)index >= (uint)Length) ThrowHelper.ThrowIndexOutOfRangeException(); return ref Array[index + Start]; } } public SegmentedArraySegment<T> Slice(int start) { if ((uint)start >= (uint)Length) ThrowHelper.ThrowArgumentOutOfRangeException(); return new SegmentedArraySegment<T>(Array, Start + start, Length - start); } public SegmentedArraySegment<T> Slice(int start, int length) { // Since start and length are both 32-bit, their sum can be computed across a 64-bit domain // without loss of fidelity. The cast to uint before the cast to ulong ensures that the // extension from 32- to 64-bit is zero-extending rather than sign-extending. The end result // of this is that if either input is negative or if the input sum overflows past Int32.MaxValue, // that information is captured correctly in the comparison against the backing _length field. if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)Length) ThrowHelper.ThrowArgumentOutOfRangeException(); return new SegmentedArraySegment<T>(Array, Start + start, length); } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/CSharp/Test/ProjectSystemShim/LegacyProject/AnalyzersTests.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Interop; using Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework; using Roslyn.Test.Utilities; using Xunit; namespace Roslyn.VisualStudio.CSharp.UnitTests.ProjectSystemShim.LegacyProject { [UseExportProvider] public class AnalyzersTests : TestBase { [WpfFact] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] public void RuleSet_GeneralOption() { var ruleSetFile = Temp.CreateFile().WriteAllText( @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Error"" /> </RuleSet> "); using var environment = new TestEnvironment(); var project = CSharpHelpers.CreateCSharpProject(environment, "Test"); var options = (CSharpCompilationOptions)environment.GetUpdatedCompilationOptionOfSingleProject(); Assert.Equal(expected: ReportDiagnostic.Default, actual: options.GeneralDiagnosticOption); ((IAnalyzerHost)project).SetRuleSetFile(ruleSetFile.Path); options = (CSharpCompilationOptions)environment.GetUpdatedCompilationOptionOfSingleProject(); Assert.Equal(expected: ReportDiagnostic.Error, actual: options.GeneralDiagnosticOption); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] public void RuleSet_CanBeFetchedFromWorkspace() { var ruleSetFile = Temp.CreateFile(); using var environment = new TestEnvironment(); var project = CSharpHelpers.CreateCSharpProject(environment, "Test"); ((IAnalyzerHost)project).SetRuleSetFile(ruleSetFile.Path); var projectId = environment.Workspace.CurrentSolution.ProjectIds.Single(); Assert.Equal(ruleSetFile.Path, environment.Workspace.TryGetRuleSetPathForProject(projectId)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] public void RuleSet_ProjectSettingOverridesGeneralOption() { var ruleSetFile = Temp.CreateFile().WriteAllText( @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> </RuleSet> "); using var environment = new TestEnvironment(); var project = CSharpHelpers.CreateCSharpProject(environment, "Test"); ((IAnalyzerHost)project).SetRuleSetFile(ruleSetFile.Path); var workspaceProject = environment.Workspace.CurrentSolution.Projects.Single(); var options = (CSharpCompilationOptions)workspaceProject.CompilationOptions; Assert.Equal(expected: ReportDiagnostic.Warn, actual: options.GeneralDiagnosticOption); project.SetOption(CompilerOptions.OPTID_WARNINGSAREERRORS, true); workspaceProject = environment.Workspace.CurrentSolution.Projects.Single(); options = (CSharpCompilationOptions)workspaceProject.CompilationOptions; Assert.Equal(expected: ReportDiagnostic.Error, actual: options.GeneralDiagnosticOption); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] public void RuleSet_SpecificOptions() { var ruleSetFile = Temp.CreateFile().WriteAllText( @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "); using var environment = new TestEnvironment(); var project = CSharpHelpers.CreateCSharpProject(environment, "Test"); ((IAnalyzerHost)project).SetRuleSetFile(ruleSetFile.Path); var options = (CSharpCompilationOptions)environment.GetUpdatedCompilationOptionOfSingleProject(); var ca1012DiagnosticOption = options.SpecificDiagnosticOptions["CA1012"]; Assert.Equal(expected: ReportDiagnostic.Error, actual: ca1012DiagnosticOption); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] public void RuleSet_ProjectSettingsOverrideSpecificOptions() { var ruleSetFile = Temp.CreateFile().WriteAllText( @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CS1014"" Action=""None"" /> </Rules> </RuleSet> "); using var environment = new TestEnvironment(); var project = CSharpHelpers.CreateCSharpProject(environment, "Test"); ((IAnalyzerHost)project).SetRuleSetFile(ruleSetFile.Path); project.SetOption(CompilerOptions.OPTID_WARNASERRORLIST, "1014"); var options = (CSharpCompilationOptions)environment.GetUpdatedCompilationOptionOfSingleProject(); var ca1014DiagnosticOption = options.SpecificDiagnosticOptions["CS1014"]; Assert.Equal(expected: ReportDiagnostic.Error, actual: ca1014DiagnosticOption); } [WpfFact, WorkItem(1087250, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087250")] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] public void SetRuleSetFile_RemoveExtraBackslashes() { var ruleSetFile = Temp.CreateFile(); using var environment = new TestEnvironment(); var project = CSharpHelpers.CreateCSharpProject(environment, "Test"); var pathWithExtraBackslashes = ruleSetFile.Path.Replace(@"\", @"\\"); ((IAnalyzerHost)project).SetRuleSetFile(pathWithExtraBackslashes); var projectRuleSetFile = project.VisualStudioProjectOptionsProcessor.ExplicitRuleSetFilePath; Assert.Equal(expected: ruleSetFile.Path, actual: projectRuleSetFile); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] [WorkItem(1092636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1092636")] [WorkItem(1040247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040247")] [WorkItem(1048368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1048368")] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_ProjectSettingsOverrideSpecificOptionsAndRestore() { var ruleSetFile = Temp.CreateFile().WriteAllText( @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CS1014"" Action=""None"" /> </Rules> </RuleSet> "); using var environment = new TestEnvironment(); var project = CSharpHelpers.CreateCSharpProject(environment, "Test"); ((IAnalyzerHost)project).SetRuleSetFile(ruleSetFile.Path); project.SetOption(CompilerOptions.OPTID_WARNASERRORLIST, "1014"); var options = environment.GetUpdatedCompilationOptionOfSingleProject(); Assert.Equal(expected: ReportDiagnostic.Error, actual: options.SpecificDiagnosticOptions["CS1014"]); project.SetOption(CompilerOptions.OPTID_WARNNOTASERRORLIST, "1014"); options = environment.GetUpdatedCompilationOptionOfSingleProject(); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: options.SpecificDiagnosticOptions["CS1014"]); project.SetOption(CompilerOptions.OPTID_WARNNOTASERRORLIST, null); options = environment.GetUpdatedCompilationOptionOfSingleProject(); Assert.Equal(expected: ReportDiagnostic.Error, actual: options.SpecificDiagnosticOptions["CS1014"]); project.SetOption(CompilerOptions.OPTID_WARNASERRORLIST, null); options = environment.GetUpdatedCompilationOptionOfSingleProject(); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: options.SpecificDiagnosticOptions["CS1014"]); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_ProjectNoWarnOverridesOtherSettings() { var ruleSetFile = Temp.CreateFile().WriteAllText( @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CS1014"" Action=""Info"" /> </Rules> </RuleSet> "); using var environment = new TestEnvironment(); var project = CSharpHelpers.CreateCSharpProject(environment, "Test"); ((IAnalyzerHost)project).SetRuleSetFile(ruleSetFile.Path); project.SetOption(CompilerOptions.OPTID_NOWARNLIST, "1014"); project.SetOption(CompilerOptions.OPTID_WARNASERRORLIST, "1014"); var workspaceProject = environment.Workspace.CurrentSolution.Projects.Single(); var options = (CSharpCompilationOptions)workspaceProject.CompilationOptions; var ca1014DiagnosticOption = options.SpecificDiagnosticOptions["CS1014"]; Assert.Equal(expected: ReportDiagnostic.Suppress, actual: ca1014DiagnosticOption); } [WpfTheory] [CombinatorialData] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] [WorkItem(33505, "https://github.com/dotnet/roslyn/pull/33505")] public async Task RuleSet_FileChangingOnDiskRefreshes(bool useCpsProject) { var ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Error"" /> </RuleSet> "; var ruleSetFile = Temp.CreateFile().WriteAllText(ruleSetSource); using var environment = new TestEnvironment(); if (useCpsProject) { await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test", binOutputPath: null, $"/ruleset:\"{ruleSetFile.Path}\""); } else { // Test legacy project handling var project = CSharpHelpers.CreateCSharpProject(environment, "Test"); ((IAnalyzerHost)project).SetRuleSetFile(ruleSetFile.Path); } var options = (CSharpCompilationOptions)environment.GetUpdatedCompilationOptionOfSingleProject(); // Assert the value exists now Assert.Equal(expected: ReportDiagnostic.Error, actual: options.GeneralDiagnosticOption); // Modify the file and raise a mock file change File.WriteAllText(ruleSetFile.Path, ruleSetSource.Replace("Error", "Warning")); environment.RaiseFileChange(ruleSetFile.Path); var listenerProvider = environment.ExportProvider.GetExportedValue<AsynchronousOperationListenerProvider>(); var waiter = listenerProvider.GetWaiter(FeatureAttribute.RuleSetEditor); waiter.ExpeditedWaitAsync().JoinUsingDispatcher(CancellationToken.None); options = (CSharpCompilationOptions)environment.GetUpdatedCompilationOptionOfSingleProject(); Assert.Equal(expected: ReportDiagnostic.Warn, actual: options.GeneralDiagnosticOption); } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Interop; using Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework; using Roslyn.Test.Utilities; using Xunit; namespace Roslyn.VisualStudio.CSharp.UnitTests.ProjectSystemShim.LegacyProject { [UseExportProvider] public class AnalyzersTests : TestBase { [WpfFact] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] public void RuleSet_GeneralOption() { var ruleSetFile = Temp.CreateFile().WriteAllText( @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Error"" /> </RuleSet> "); using var environment = new TestEnvironment(); var project = CSharpHelpers.CreateCSharpProject(environment, "Test"); var options = (CSharpCompilationOptions)environment.GetUpdatedCompilationOptionOfSingleProject(); Assert.Equal(expected: ReportDiagnostic.Default, actual: options.GeneralDiagnosticOption); ((IAnalyzerHost)project).SetRuleSetFile(ruleSetFile.Path); options = (CSharpCompilationOptions)environment.GetUpdatedCompilationOptionOfSingleProject(); Assert.Equal(expected: ReportDiagnostic.Error, actual: options.GeneralDiagnosticOption); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] public void RuleSet_CanBeFetchedFromWorkspace() { var ruleSetFile = Temp.CreateFile(); using var environment = new TestEnvironment(); var project = CSharpHelpers.CreateCSharpProject(environment, "Test"); ((IAnalyzerHost)project).SetRuleSetFile(ruleSetFile.Path); var projectId = environment.Workspace.CurrentSolution.ProjectIds.Single(); Assert.Equal(ruleSetFile.Path, environment.Workspace.TryGetRuleSetPathForProject(projectId)); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] public void RuleSet_ProjectSettingOverridesGeneralOption() { var ruleSetFile = Temp.CreateFile().WriteAllText( @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> </RuleSet> "); using var environment = new TestEnvironment(); var project = CSharpHelpers.CreateCSharpProject(environment, "Test"); ((IAnalyzerHost)project).SetRuleSetFile(ruleSetFile.Path); var workspaceProject = environment.Workspace.CurrentSolution.Projects.Single(); var options = (CSharpCompilationOptions)workspaceProject.CompilationOptions; Assert.Equal(expected: ReportDiagnostic.Warn, actual: options.GeneralDiagnosticOption); project.SetOption(CompilerOptions.OPTID_WARNINGSAREERRORS, true); workspaceProject = environment.Workspace.CurrentSolution.Projects.Single(); options = (CSharpCompilationOptions)workspaceProject.CompilationOptions; Assert.Equal(expected: ReportDiagnostic.Error, actual: options.GeneralDiagnosticOption); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] public void RuleSet_SpecificOptions() { var ruleSetFile = Temp.CreateFile().WriteAllText( @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "); using var environment = new TestEnvironment(); var project = CSharpHelpers.CreateCSharpProject(environment, "Test"); ((IAnalyzerHost)project).SetRuleSetFile(ruleSetFile.Path); var options = (CSharpCompilationOptions)environment.GetUpdatedCompilationOptionOfSingleProject(); var ca1012DiagnosticOption = options.SpecificDiagnosticOptions["CA1012"]; Assert.Equal(expected: ReportDiagnostic.Error, actual: ca1012DiagnosticOption); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] public void RuleSet_ProjectSettingsOverrideSpecificOptions() { var ruleSetFile = Temp.CreateFile().WriteAllText( @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CS1014"" Action=""None"" /> </Rules> </RuleSet> "); using var environment = new TestEnvironment(); var project = CSharpHelpers.CreateCSharpProject(environment, "Test"); ((IAnalyzerHost)project).SetRuleSetFile(ruleSetFile.Path); project.SetOption(CompilerOptions.OPTID_WARNASERRORLIST, "1014"); var options = (CSharpCompilationOptions)environment.GetUpdatedCompilationOptionOfSingleProject(); var ca1014DiagnosticOption = options.SpecificDiagnosticOptions["CS1014"]; Assert.Equal(expected: ReportDiagnostic.Error, actual: ca1014DiagnosticOption); } [WpfFact, WorkItem(1087250, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087250")] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] public void SetRuleSetFile_RemoveExtraBackslashes() { var ruleSetFile = Temp.CreateFile(); using var environment = new TestEnvironment(); var project = CSharpHelpers.CreateCSharpProject(environment, "Test"); var pathWithExtraBackslashes = ruleSetFile.Path.Replace(@"\", @"\\"); ((IAnalyzerHost)project).SetRuleSetFile(pathWithExtraBackslashes); var projectRuleSetFile = project.VisualStudioProjectOptionsProcessor.ExplicitRuleSetFilePath; Assert.Equal(expected: ruleSetFile.Path, actual: projectRuleSetFile); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] [WorkItem(1092636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1092636")] [WorkItem(1040247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040247")] [WorkItem(1048368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1048368")] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_ProjectSettingsOverrideSpecificOptionsAndRestore() { var ruleSetFile = Temp.CreateFile().WriteAllText( @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CS1014"" Action=""None"" /> </Rules> </RuleSet> "); using var environment = new TestEnvironment(); var project = CSharpHelpers.CreateCSharpProject(environment, "Test"); ((IAnalyzerHost)project).SetRuleSetFile(ruleSetFile.Path); project.SetOption(CompilerOptions.OPTID_WARNASERRORLIST, "1014"); var options = environment.GetUpdatedCompilationOptionOfSingleProject(); Assert.Equal(expected: ReportDiagnostic.Error, actual: options.SpecificDiagnosticOptions["CS1014"]); project.SetOption(CompilerOptions.OPTID_WARNNOTASERRORLIST, "1014"); options = environment.GetUpdatedCompilationOptionOfSingleProject(); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: options.SpecificDiagnosticOptions["CS1014"]); project.SetOption(CompilerOptions.OPTID_WARNNOTASERRORLIST, null); options = environment.GetUpdatedCompilationOptionOfSingleProject(); Assert.Equal(expected: ReportDiagnostic.Error, actual: options.SpecificDiagnosticOptions["CS1014"]); project.SetOption(CompilerOptions.OPTID_WARNASERRORLIST, null); options = environment.GetUpdatedCompilationOptionOfSingleProject(); Assert.Equal(expected: ReportDiagnostic.Suppress, actual: options.SpecificDiagnosticOptions["CS1014"]); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] [WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")] public void RuleSet_ProjectNoWarnOverridesOtherSettings() { var ruleSetFile = Temp.CreateFile().WriteAllText( @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CS1014"" Action=""Info"" /> </Rules> </RuleSet> "); using var environment = new TestEnvironment(); var project = CSharpHelpers.CreateCSharpProject(environment, "Test"); ((IAnalyzerHost)project).SetRuleSetFile(ruleSetFile.Path); project.SetOption(CompilerOptions.OPTID_NOWARNLIST, "1014"); project.SetOption(CompilerOptions.OPTID_WARNASERRORLIST, "1014"); var workspaceProject = environment.Workspace.CurrentSolution.Projects.Single(); var options = (CSharpCompilationOptions)workspaceProject.CompilationOptions; var ca1014DiagnosticOption = options.SpecificDiagnosticOptions["CS1014"]; Assert.Equal(expected: ReportDiagnostic.Suppress, actual: ca1014DiagnosticOption); } [WpfTheory] [CombinatorialData] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] [WorkItem(33505, "https://github.com/dotnet/roslyn/pull/33505")] public async Task RuleSet_FileChangingOnDiskRefreshes(bool useCpsProject) { var ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Error"" /> </RuleSet> "; var ruleSetFile = Temp.CreateFile().WriteAllText(ruleSetSource); using var environment = new TestEnvironment(); if (useCpsProject) { await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test", binOutputPath: null, $"/ruleset:\"{ruleSetFile.Path}\""); } else { // Test legacy project handling var project = CSharpHelpers.CreateCSharpProject(environment, "Test"); ((IAnalyzerHost)project).SetRuleSetFile(ruleSetFile.Path); } var options = (CSharpCompilationOptions)environment.GetUpdatedCompilationOptionOfSingleProject(); // Assert the value exists now Assert.Equal(expected: ReportDiagnostic.Error, actual: options.GeneralDiagnosticOption); // Modify the file and raise a mock file change File.WriteAllText(ruleSetFile.Path, ruleSetSource.Replace("Error", "Warning")); environment.RaiseFileChange(ruleSetFile.Path); var listenerProvider = environment.ExportProvider.GetExportedValue<AsynchronousOperationListenerProvider>(); var waiter = listenerProvider.GetWaiter(FeatureAttribute.RuleSetEditor); waiter.ExpeditedWaitAsync().JoinUsingDispatcher(CancellationToken.None); options = (CSharpCompilationOptions)environment.GetUpdatedCompilationOptionOfSingleProject(); Assert.Equal(expected: ReportDiagnostic.Warn, actual: options.GeneralDiagnosticOption); } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Test/Semantic/Semantics/TopLevelStatementsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.TopLevelStatements)] public class TopLevelStatementsTests : CompilingTestBase { private static CSharpParseOptions DefaultParseOptions => TestOptions.Regular9; private static bool IsNullableAnalysisEnabled(CSharpCompilation compilation) { var type = compilation.GlobalNamespace.GetMembers().OfType<SimpleProgramNamedTypeSymbol>().Single(); var methods = type.GetMembers().OfType<SynthesizedSimpleProgramEntryPointSymbol>(); return methods.Any(m => m.IsNullableAnalysisEnabled()); } [Fact] public void Simple_01() { var text = @"System.Console.WriteLine(""Hi!"");"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); Assert.True(entryPoint.ReturnsVoid); AssertEntryPointParameter(entryPoint); CompileAndVerify(comp, expectedOutput: "Hi!"); Assert.Same(entryPoint, comp.GetEntryPoint(default)); Assert.False(entryPoint.CanBeReferencedByName); Assert.False(entryPoint.ContainingType.CanBeReferencedByName); Assert.Equal("<Main>$", entryPoint.Name); Assert.Equal("<Program>$", entryPoint.ContainingType.Name); } private static void AssertEntryPointParameter(SynthesizedSimpleProgramEntryPointSymbol entryPoint) { Assert.Equal(1, entryPoint.ParameterCount); ParameterSymbol parameter = entryPoint.Parameters.Single(); Assert.Equal("System.String[] args", parameter.ToTestDisplayString(includeNonNullable: true)); Assert.True(parameter.IsImplicitlyDeclared); Assert.Same(entryPoint, parameter.ContainingSymbol); } [Fact] public void Simple_02() { var text = @" using System; using System.Threading.Tasks; Console.Write(""hello ""); await Task.Factory.StartNew(() => 5); Console.Write(""async main""); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); AssertEntryPointParameter(entryPoint); CompileAndVerify(comp, expectedOutput: "hello async main"); } [Fact] public void Simple_03() { var text1 = @" System.Console.Write(""1""); "; var text2 = @" // System.Console.Write(""2""); System.Console.WriteLine(); System.Console.WriteLine(); "; var text3 = @" // // System.Console.Write(""3""); System.Console.WriteLine(); System.Console.WriteLine(); "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,1): error CS8802: Only one compilation unit can have top-level statements. // System.Console.Write("2"); Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "System").WithLocation(3, 1) ); comp = CreateCompilation(new[] { text1, text2, text3 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,1): error CS8802: Only one compilation unit can have top-level statements. // System.Console.Write("2"); Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "System").WithLocation(3, 1), // (4,1): error CS8802: Only one compilation unit can have top-level statements. // System.Console.Write("3"); Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "System").WithLocation(4, 1) ); } [Fact] public void Simple_04() { var text = @" Type.M(); static class Type { public static void M() { System.Console.WriteLine(""Hi!""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void Simple_05() { var text1 = @" Type.M(); "; var text2 = @" static class Type { public static void M() { System.Console.WriteLine(""Hi!""); } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); comp = CreateCompilation(new[] { text2, text1 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void Simple_06_01() { var text1 = @" local(); void local() => System.Console.WriteLine(2); "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "2"); verifyModel(comp, comp.SyntaxTrees[0]); comp = CreateCompilation(text1, options: TestOptions.DebugExe.WithNullableContextOptions(NullableContextOptions.Enable), parseOptions: DefaultParseOptions); verifyModel(comp, comp.SyntaxTrees[0], nullableEnabled: true); static void verifyModel(CSharpCompilation comp, SyntaxTree tree1, bool nullableEnabled = false) { Assert.Equal(nullableEnabled, IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var model1 = comp.GetSemanticModel(tree1); verifyModelForGlobalStatements(tree1, model1); var unit1 = (CompilationUnitSyntax)tree1.GetRoot(); var localRef = unit1.DescendantNodes().OfType<IdentifierNameSyntax>().First(); var refSymbol = model1.GetSymbolInfo(localRef).Symbol; Assert.Equal("void local()", refSymbol.ToTestDisplayString()); Assert.Contains(refSymbol.Name, model1.LookupNames(localRef.SpanStart)); Assert.Contains(refSymbol, model1.LookupSymbols(localRef.SpanStart)); Assert.Same(refSymbol, model1.LookupSymbols(localRef.SpanStart, name: refSymbol.Name).Single()); var operation1 = model1.GetOperation(localRef.Parent); Assert.NotNull(operation1); Assert.IsAssignableFrom<IInvocationOperation>(operation1); Assert.NotNull(ControlFlowGraph.Create((IMethodBodyOperation)((IBlockOperation)operation1.Parent.Parent).Parent)); model1.VerifyOperationTree(unit1, @" IMethodBodyOperation (OperationKind.MethodBody, Type: null) (Syntax: 'local(); ... iteLine(2);') BlockBody: IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'local(); ... iteLine(2);') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'local();') Expression: IInvocationOperation (void local()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'local()') Instance Receiver: null Arguments(0) ILocalFunctionOperation (Symbol: void local()) (OperationKind.LocalFunction, Type: null) (Syntax: 'void local( ... iteLine(2);') IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '=> System.C ... riteLine(2)') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'System.Cons ... riteLine(2)') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(2)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '=> System.C ... riteLine(2)') ReturnedValue: null ExpressionBody: null "); var localDecl = unit1.DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Same(declSymbol.ContainingSymbol, model1.GetDeclaredSymbol(unit1)); Assert.Same(declSymbol.ContainingSymbol, model1.GetDeclaredSymbol((SyntaxNode)unit1)); Assert.Same(refSymbol, declSymbol); Assert.Contains(declSymbol.Name, model1.LookupNames(localDecl.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localDecl.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: declSymbol.Name).Single()); var operation2 = model1.GetOperation(localDecl); Assert.NotNull(operation2); Assert.IsAssignableFrom<ILocalFunctionOperation>(operation2); static void verifyModelForGlobalStatements(SyntaxTree tree1, SemanticModel model1) { var symbolInfo = model1.GetSymbolInfo(tree1.GetRoot()); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); var typeInfo = model1.GetTypeInfo(tree1.GetRoot()); Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); foreach (var globalStatement in tree1.GetRoot().DescendantNodes().OfType<GlobalStatementSyntax>()) { symbolInfo = model1.GetSymbolInfo(globalStatement); Assert.Null(model1.GetOperation(globalStatement)); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); typeInfo = model1.GetTypeInfo(globalStatement); Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); } } } } [Fact] public void Simple_06_02() { var text1 = @"local();"; var text2 = @"void local() => System.Console.WriteLine(2);"; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS8802: Only one compilation unit can have top-level statements. // void local() => System.Console.WriteLine(2); Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "void").WithLocation(1, 1), // (1,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(1, 1), // (1,6): warning CS8321: The local function 'local' is declared but never used // void local() => System.Console.WriteLine(2); Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(1, 6) ); verifyModel(comp, comp.SyntaxTrees[0], comp.SyntaxTrees[1]); comp = CreateCompilation(new[] { text2, text1 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS8802: Only one compilation unit can have top-level statements. // local(); Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "local").WithLocation(1, 1), // (1,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(1, 1), // (1,6): warning CS8321: The local function 'local' is declared but never used // void local() => System.Console.WriteLine(2); Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(1, 6) ); verifyModel(comp, comp.SyntaxTrees[1], comp.SyntaxTrees[0]); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe.WithNullableContextOptions(NullableContextOptions.Enable), parseOptions: DefaultParseOptions); verifyModel(comp, comp.SyntaxTrees[0], comp.SyntaxTrees[1], nullableEnabled: true); static void verifyModel(CSharpCompilation comp, SyntaxTree tree1, SyntaxTree tree2, bool nullableEnabled = false) { Assert.Equal(nullableEnabled, IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var model1 = comp.GetSemanticModel(tree1); verifyModelForGlobalStatements(tree1, model1); var unit1 = (CompilationUnitSyntax)tree1.GetRoot(); var localRef = unit1.DescendantNodes().OfType<IdentifierNameSyntax>().Single(); var refSymbol = model1.GetSymbolInfo(localRef).Symbol; var refMethod = model1.GetDeclaredSymbol(unit1); Assert.NotNull(refMethod); Assert.Null(refSymbol); var name = localRef.Identifier.ValueText; Assert.DoesNotContain(name, model1.LookupNames(localRef.SpanStart)); Assert.Empty(model1.LookupSymbols(localRef.SpanStart).Where(s => s.Name == name)); Assert.Empty(model1.LookupSymbols(localRef.SpanStart, name: name)); var operation1 = model1.GetOperation(localRef.Parent); Assert.NotNull(operation1); Assert.IsAssignableFrom<IInvalidOperation>(operation1); Assert.NotNull(ControlFlowGraph.Create((IMethodBodyOperation)((IBlockOperation)operation1.Parent.Parent).Parent)); model1.VerifyOperationTree(unit1, @" IMethodBodyOperation (OperationKind.MethodBody, Type: null, IsInvalid) (Syntax: 'local();') BlockBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'local();') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'local();') Expression: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'local()') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'local') Children(0) ExpressionBody: null "); SyntaxTreeSemanticModel syntaxTreeModel = ((SyntaxTreeSemanticModel)model1); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[unit1]; var model2 = comp.GetSemanticModel(tree2); verifyModelForGlobalStatements(tree2, model2); var unit2 = (CompilationUnitSyntax)tree2.GetRoot(); var declMethod = model2.GetDeclaredSymbol(unit2); var localDecl = unit2.DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single(); var declSymbol = model2.GetDeclaredSymbol(localDecl); Assert.Equal("void local()", declSymbol.ToTestDisplayString()); Assert.Same(declSymbol.ContainingSymbol, declMethod); Assert.NotEqual(refMethod, declMethod); Assert.Contains(declSymbol.Name, model2.LookupNames(localDecl.SpanStart)); Assert.Contains(declSymbol, model2.LookupSymbols(localDecl.SpanStart)); Assert.Same(declSymbol, model2.LookupSymbols(localDecl.SpanStart, name: declSymbol.Name).Single()); var operation2 = model2.GetOperation(localDecl); Assert.NotNull(operation2); Assert.IsAssignableFrom<ILocalFunctionOperation>(operation2); Assert.NotNull(ControlFlowGraph.Create((IMethodBodyOperation)((IBlockOperation)operation2.Parent).Parent)); var isInvalid = comp.SyntaxTrees[1] == tree2 ? ", IsInvalid" : ""; model2.VerifyOperationTree(unit2, @" IMethodBodyOperation (OperationKind.MethodBody, Type: null" + isInvalid + @") (Syntax: 'void local( ... iteLine(2);') BlockBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null" + isInvalid + @", IsImplicit) (Syntax: 'void local( ... iteLine(2);') ILocalFunctionOperation (Symbol: void local()) (OperationKind.LocalFunction, Type: null" + isInvalid + @") (Syntax: 'void local( ... iteLine(2);') IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '=> System.C ... riteLine(2)') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'System.Cons ... riteLine(2)') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(2)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '=> System.C ... riteLine(2)') ReturnedValue: null ExpressionBody: null "); static void verifyModelForGlobalStatements(SyntaxTree tree1, SemanticModel model1) { var symbolInfo = model1.GetSymbolInfo(tree1.GetRoot()); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); var typeInfo = model1.GetTypeInfo(tree1.GetRoot()); Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); foreach (var globalStatement in tree1.GetRoot().DescendantNodes().OfType<GlobalStatementSyntax>()) { symbolInfo = model1.GetSymbolInfo(globalStatement); Assert.Null(model1.GetOperation(globalStatement)); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); typeInfo = model1.GetTypeInfo(globalStatement); Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); } } } } [Fact] public void Simple_07() { var text1 = @" var i = 1; local(); "; var text2 = @" void local() => System.Console.WriteLine(i); "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // void local() => System.Console.WriteLine(i); Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "void").WithLocation(2, 1), // (2,5): warning CS0219: The variable 'i' is assigned but its value is never used // var i = 1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(2, 5), // (2,6): warning CS8321: The local function 'local' is declared but never used // void local() => System.Console.WriteLine(i); Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(2, 6), // (2,42): error CS0103: The name 'i' does not exist in the current context // void local() => System.Console.WriteLine(i); Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(2, 42), // (3,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(3, 1) ); verifyModel(comp, comp.SyntaxTrees[0], comp.SyntaxTrees[1]); comp = CreateCompilation(new[] { text2, text1 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // var i = 1; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "var").WithLocation(2, 1), // (2,5): warning CS0219: The variable 'i' is assigned but its value is never used // var i = 1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(2, 5), // (2,6): warning CS8321: The local function 'local' is declared but never used // void local() => System.Console.WriteLine(i); Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(2, 6), // (2,42): error CS0103: The name 'i' does not exist in the current context // void local() => System.Console.WriteLine(i); Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(2, 42), // (3,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(3, 1) ); verifyModel(comp, comp.SyntaxTrees[1], comp.SyntaxTrees[0]); static void verifyModel(CSharpCompilation comp, SyntaxTree tree1, SyntaxTree tree2) { Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.Int32 i", declSymbol.ToTestDisplayString()); Assert.Contains(declSymbol.Name, model1.LookupNames(localDecl.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localDecl.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: declSymbol.Name).Single()); Assert.NotNull(model1.GetOperation(tree1.GetRoot())); var operation1 = model1.GetOperation(localDecl); Assert.NotNull(operation1); Assert.IsAssignableFrom<IVariableDeclaratorOperation>(operation1); var localFuncRef = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "local").Single(); Assert.Contains(declSymbol.Name, model1.LookupNames(localFuncRef.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localFuncRef.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localFuncRef.SpanStart, name: declSymbol.Name).Single()); Assert.DoesNotContain(declSymbol, model1.AnalyzeDataFlow(localDecl.Ancestors().OfType<StatementSyntax>().First()).DataFlowsOut); var model2 = comp.GetSemanticModel(tree2); var localRef = tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "i").Single(); var refSymbol = model2.GetSymbolInfo(localRef).Symbol; Assert.Null(refSymbol); var name = localRef.Identifier.ValueText; Assert.DoesNotContain(name, model2.LookupNames(localRef.SpanStart)); Assert.Empty(model2.LookupSymbols(localRef.SpanStart).Where(s => s.Name == name)); Assert.Empty(model2.LookupSymbols(localRef.SpanStart, name: name)); Assert.NotNull(model2.GetOperation(tree2.GetRoot())); var operation2 = model2.GetOperation(localRef); Assert.NotNull(operation2); Assert.IsAssignableFrom<IInvalidOperation>(operation2); Assert.DoesNotContain(declSymbol, model2.AnalyzeDataFlow(localRef).DataFlowsIn); } } [Fact] public void Simple_08() { var text1 = @" var i = 1; System.Console.Write(i++); System.Console.Write(i); "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "12"); var tree1 = comp.SyntaxTrees[0]; Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.Int32 i", declSymbol.ToTestDisplayString()); Assert.Contains(declSymbol.Name, model1.LookupNames(localDecl.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localDecl.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: declSymbol.Name).Single()); var localRefs = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "i").ToArray(); Assert.Equal(2, localRefs.Length); foreach (var localRef in localRefs) { var refSymbol = model1.GetSymbolInfo(localRef).Symbol; Assert.Same(declSymbol, refSymbol); Assert.Contains(declSymbol.Name, model1.LookupNames(localRef.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localRef.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localRef.SpanStart, name: declSymbol.Name).Single()); } } [Fact] public void Simple_09() { var text1 = @" var i = 1; local(); void local() => System.Console.WriteLine(i); "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "1"); verifyModel(comp, comp.SyntaxTrees[0]); static void verifyModel(CSharpCompilation comp, SyntaxTree tree1) { Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.Int32 i", declSymbol.ToTestDisplayString()); Assert.Contains(declSymbol.Name, model1.LookupNames(localDecl.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localDecl.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: declSymbol.Name).Single()); Assert.NotNull(model1.GetOperation(tree1.GetRoot())); var operation1 = model1.GetOperation(localDecl); Assert.NotNull(operation1); Assert.IsAssignableFrom<IVariableDeclaratorOperation>(operation1); var localFuncRef = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "local").Single(); Assert.Contains(declSymbol.Name, model1.LookupNames(localFuncRef.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localFuncRef.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localFuncRef.SpanStart, name: declSymbol.Name).Single()); Assert.Contains(declSymbol, model1.AnalyzeDataFlow(localDecl.Ancestors().OfType<StatementSyntax>().First()).DataFlowsOut); var localRef = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "i").Single(); var refSymbol = model1.GetSymbolInfo(localRef).Symbol; Assert.Same(declSymbol, refSymbol); Assert.Contains(refSymbol.Name, model1.LookupNames(localRef.SpanStart)); Assert.Contains(refSymbol, model1.LookupSymbols(localRef.SpanStart)); Assert.Same(refSymbol, model1.LookupSymbols(localRef.SpanStart, name: refSymbol.Name).Single()); var operation2 = model1.GetOperation(localRef); Assert.NotNull(operation2); Assert.IsAssignableFrom<ILocalReferenceOperation>(operation2); // The following assert fails due to https://github.com/dotnet/roslyn/issues/41853, enable once the issue is fixed. //Assert.Contains(declSymbol, model1.AnalyzeDataFlow(localRef).DataFlowsIn); } } [Fact] public void LanguageVersion_01() { var text = @"System.Console.WriteLine(""Hi!"");"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (1,1): error CS8400: Feature 'top-level statements' is not available in C# 8.0. Please use language version 9.0 or greater. // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, @"System.Console.WriteLine(""Hi!"");").WithArguments("top-level statements", "9.0").WithLocation(1, 1) ); } [Fact] public void WithinType_01() { var text = @" class Test { System.Console.WriteLine(""Hi!""); } "; var comp = CreateCompilation(text, parseOptions: DefaultParseOptions); var expected = new[] { // (4,29): error CS1519: Invalid token '(' in class, record, struct, or interface member declaration // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "(").WithArguments("(").WithLocation(4, 29), // (4,30): error CS1031: Type expected // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_TypeExpected, @"""Hi!""").WithLocation(4, 30), // (4,30): error CS8124: Tuple must contain at least two elements. // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_TupleTooFewElements, @"""Hi!""").WithLocation(4, 30), // (4,30): error CS1026: ) expected // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_CloseParenExpected, @"""Hi!""").WithLocation(4, 30), // (4,30): error CS1519: Invalid token '"Hi!"' in class, record, struct, or interface member declaration // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, @"""Hi!""").WithArguments(@"""Hi!""").WithLocation(4, 30) }; comp.GetDiagnostics(CompilationStage.Parse, includeEarlierStages: false, cancellationToken: default).Verify(expected); comp.VerifyDiagnostics(expected); } [Fact] public void WithinNamespace_01() { var text = @" namespace Test { System.Console.WriteLine(""Hi!""); } "; var comp = CreateCompilation(text, parseOptions: DefaultParseOptions); var expected = new[] { // (4,20): error CS0116: A namespace cannot directly contain members such as fields or methods // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "WriteLine").WithLocation(4, 20), // (4,30): error CS1026: ) expected // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_CloseParenExpected, @"""Hi!""").WithLocation(4, 30), // (4,30): error CS1022: Type or namespace definition, or end-of-file expected // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_EOFExpected, @"""Hi!""").WithLocation(4, 30) }; comp.GetDiagnostics(CompilationStage.Parse, includeEarlierStages: false, cancellationToken: default).Verify(expected); comp.VerifyDiagnostics(expected); } [Fact] public void LocalDeclarationStatement_01() { var text = @" string s = ""Hi!""; System.Console.WriteLine(s); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var reference = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "s").Single(); var local = model.GetDeclaredSymbol(declarator); Assert.Same(local, model.GetSymbolInfo(reference).Symbol); Assert.Equal("System.String s", local.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, local.Kind); Assert.Equal(SymbolKind.Method, local.ContainingSymbol.Kind); Assert.False(local.ContainingSymbol.IsImplicitlyDeclared); Assert.Equal(SymbolKind.NamedType, local.ContainingSymbol.ContainingSymbol.Kind); Assert.False(local.ContainingSymbol.ContainingSymbol.IsImplicitlyDeclared); Assert.True(((INamespaceSymbol)local.ContainingSymbol.ContainingSymbol.ContainingSymbol).IsGlobalNamespace); } [Fact] public void LocalDeclarationStatement_02() { var text = @" new string a = ""Hi!""; System.Console.WriteLine(a); public string b = ""Hi!""; System.Console.WriteLine(b); static string c = ""Hi!""; System.Console.WriteLine(c); readonly string d = ""Hi!""; System.Console.WriteLine(d); volatile string e = ""Hi!""; System.Console.WriteLine(e); [System.Obsolete()] string f = ""Hi!""; System.Console.WriteLine(f); [System.Obsolete()] const string g = ""Hi!""; System.Console.WriteLine(g); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,12): error CS0116: A namespace cannot directly contain members such as fields or methods // new string a = "Hi!"; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "a").WithLocation(2, 12), // (2,12): warning CS0109: The member '<invalid-global-code>.a' does not hide an accessible member. The new keyword is not required. // new string a = "Hi!"; Diagnostic(ErrorCode.WRN_NewNotRequired, "a").WithArguments("<invalid-global-code>.a").WithLocation(2, 12), // (3,26): error CS0103: The name 'a' does not exist in the current context // System.Console.WriteLine(a); Diagnostic(ErrorCode.ERR_NameNotInContext, "a").WithArguments("a").WithLocation(3, 26), // (4,15): error CS0116: A namespace cannot directly contain members such as fields or methods // public string b = "Hi!"; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "b").WithLocation(4, 15), // (5,26): error CS0103: The name 'b' does not exist in the current context // System.Console.WriteLine(b); Diagnostic(ErrorCode.ERR_NameNotInContext, "b").WithArguments("b").WithLocation(5, 26), // (6,1): error CS0106: The modifier 'static' is not valid for this item // static string c = "Hi!"; Diagnostic(ErrorCode.ERR_BadMemberFlag, "static").WithArguments("static").WithLocation(6, 1), // (8,1): error CS0106: The modifier 'readonly' is not valid for this item // readonly string d = "Hi!"; Diagnostic(ErrorCode.ERR_BadMemberFlag, "readonly").WithArguments("readonly").WithLocation(8, 1), // (10,1): error CS0106: The modifier 'volatile' is not valid for this item // volatile string e = "Hi!"; Diagnostic(ErrorCode.ERR_BadMemberFlag, "volatile").WithArguments("volatile").WithLocation(10, 1), // (12,1): error CS7014: Attributes are not valid in this context. // [System.Obsolete()] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[System.Obsolete()]").WithLocation(12, 1), // (15,1): error CS7014: Attributes are not valid in this context. // [System.Obsolete()] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[System.Obsolete()]").WithLocation(15, 1) ); } [Fact] public void LocalDeclarationStatement_03() { var text = @" string a = ""1""; string a = ""2""; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,8): warning CS0219: The variable 'a' is assigned but its value is never used // string a = "1"; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(2, 8), // (3,8): error CS0128: A local variable or function named 'a' is already defined in this scope // string a = "2"; Diagnostic(ErrorCode.ERR_LocalDuplicate, "a").WithArguments("a").WithLocation(3, 8), // (3,8): warning CS0219: The variable 'a' is assigned but its value is never used // string a = "2"; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(3, 8) ); } [Fact] public void LocalDeclarationStatement_04() { var text = @" using System; using System.Threading.Tasks; var s = await local(); System.Console.WriteLine(s); async Task<string> local() { await Task.Factory.StartNew(() => 5); return ""Hi!""; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void LocalDeclarationStatement_05() { var text = @" const string s = ""Hi!""; System.Console.WriteLine(s); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void LocalDeclarationStatement_06() { var text = @" a.ToString(); string a = ""2""; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS0841: Cannot use local variable 'a' before it is declared // a.ToString(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "a").WithArguments("a").WithLocation(2, 1) ); } [Fact] public void LocalDeclarationStatement_07() { var text1 = @" string x = ""1""; System.Console.Write(x); "; var text2 = @" int x = 1; System.Console.Write(x); "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // int x = 1; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "int").WithLocation(2, 1) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var symbol1 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single()); Assert.Equal("System.String x", symbol1.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Single()).Symbol); var tree2 = comp.SyntaxTrees[1]; var model2 = comp.GetSemanticModel(tree2); var symbol2 = model2.GetDeclaredSymbol(tree2.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single()); Assert.Equal("System.Int32 x", symbol2.ToTestDisplayString()); Assert.Same(symbol2, model2.GetSymbolInfo(tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Single()).Symbol); } [Fact] public void LocalDeclarationStatement_08() { var text = @" int a = 0; int b = 0; int c = -100; ref int d = ref c; d = 300; d = ref local(true, ref a, ref b); d = 100; d = ref local(false, ref a, ref b); d = 200; System.Console.Write(a); System.Console.Write(' '); System.Console.Write(b); System.Console.Write(' '); System.Console.Write(c); ref int local(bool flag, ref int a, ref int b) { return ref flag ? ref a : ref b; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "100 200 300", verify: Verification.Skipped); } [Fact] public void LocalDeclarationStatement_09() { var text = @" using var a = new MyDisposable(); System.Console.Write(1); class MyDisposable : System.IDisposable { public void Dispose() { System.Console.Write(2); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "12", verify: Verification.Skipped); } [Fact] public void LocalDeclarationStatement_10() { string source = @" await using var x = new C(); System.Console.Write(""body ""); class C : System.IAsyncDisposable, System.IDisposable { public System.Threading.Tasks.ValueTask DisposeAsync() { System.Console.Write(""DisposeAsync""); return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask); } public void Dispose() { System.Console.Write(""IGNORED""); } } "; var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "body DisposeAsync"); } [Fact] public void LocalDeclarationStatement_11() { var text1 = @" string x = ""1""; System.Console.Write(x); int x = 1; System.Console.Write(x); "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,5): error CS0128: A local variable or function named 'x' is already defined in this scope // int x = 1; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x").WithArguments("x").WithLocation(4, 5), // (4,5): warning CS0219: The variable 'x' is assigned but its value is never used // int x = 1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(4, 5) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var symbol1 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First()); Assert.Equal("System.String x", symbol1.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").First()).Symbol); var symbol2 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Skip(1).Single()); Assert.Equal("System.Int32 x", symbol2.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Skip(1).Single()).Symbol); } [Fact] public void LocalDeclarationStatement_12() { var text = @" (int x, int y) = (1, 2); System.Console.WriteLine(x+y); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "3"); } [Fact] public void LocalDeclarationStatement_13() { var text = @" var (x, y) = (1, 2); System.Console.WriteLine(x+y); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "3"); } [Fact] public void LocalDeclarationStatement_14() { var text1 = @" string args = ""1""; System.Console.Write(args); "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,8): error CS0136: A local or parameter named 'args' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // string args = "1"; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "args").WithArguments("args").WithLocation(2, 8) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var symbol1 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First()); Assert.Equal("System.String args", symbol1.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "args").Single()).Symbol); } [Fact] public void LocalDeclarationStatement_15() { var text1 = @" using System.Linq; string x = null; _ = from x in new object[0] select x; System.Console.Write(x); "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,10): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // _ = from x in new object[0] select x; Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(4, 10) ); } [Fact] public void LocalDeclarationStatement_16() { var text = @" System.Console.WriteLine(); string await = ""Hi!""; System.Console.WriteLine(await); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,8): error CS4003: 'await' cannot be used as an identifier within an async method or lambda expression // string await = "Hi!"; Diagnostic(ErrorCode.ERR_BadAwaitAsIdentifier, "await").WithLocation(3, 8), // (3,8): warning CS0219: The variable 'await' is assigned but its value is never used // string await = "Hi!"; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "await").WithArguments("await").WithLocation(3, 8), // (4,31): error CS1525: Invalid expression term ')' // System.Console.WriteLine(await); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(4, 31) ); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnType.IsErrorType()); AssertEntryPointParameter(entryPoint); } [Fact] public void LocalDeclarationStatement_17() { var text = @" string async = ""Hi!""; System.Console.WriteLine(async); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void LocalDeclarationStatement_18() { var text = @" int c = -100; ref int d = ref c; System.Console.Write(d); await System.Threading.Tasks.Task.Yield(); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,9): error CS8177: Async methods cannot have by-reference locals // ref int d = ref c; Diagnostic(ErrorCode.ERR_BadAsyncLocalType, "d").WithLocation(3, 9) ); } [Fact] public void UsingStatement_01() { string source = @" await using (var x = new C()) { System.Console.Write(""body ""); } class C : System.IAsyncDisposable, System.IDisposable { public System.Threading.Tasks.ValueTask DisposeAsync() { System.Console.Write(""DisposeAsync""); return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask); } public void Dispose() { System.Console.Write(""IGNORED""); } } "; var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "body DisposeAsync"); } [Fact] public void UsingStatement_02() { string source = @" await using (new C()) { System.Console.Write(""body ""); } class C : System.IAsyncDisposable, System.IDisposable { public System.Threading.Tasks.ValueTask DisposeAsync() { System.Console.Write(""DisposeAsync""); return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask); } public void Dispose() { System.Console.Write(""IGNORED""); } } "; var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "body DisposeAsync"); } [Fact] public void UsingStatement_03() { string source = @" using (new C()) { System.Console.Write(""body ""); } class C : System.IDisposable { public void Dispose() { System.Console.Write(""Dispose""); } } "; var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "body Dispose"); } [Fact] public void ForeachStatement_01() { string source = @" using System.Threading.Tasks; await foreach (var i in new C()) { } System.Console.Write(""Done""); class C { public Enumerator GetAsyncEnumerator() { return new Enumerator(); } public sealed class Enumerator { public async Task<bool> MoveNextAsync() { System.Console.Write(""MoveNextAsync ""); await Task.Yield(); return false; } public int Current { get => throw null; } public async Task DisposeAsync() { System.Console.Write(""DisposeAsync ""); await Task.Yield(); } } } "; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "MoveNextAsync DisposeAsync Done"); } [Fact] public void ForeachStatement_02() { var text = @" int i = 0; foreach (var j in new [] {2, 3}) { i += j; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "5"); } [Fact] public void ForeachStatement_03() { var text = @" int i = 0; foreach (var (j, k) in new [] {(2,200), (3,300)}) { i += j; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "5"); } [Fact] public void LocalUsedBeforeDeclaration_01() { var text1 = @" const string x = y; System.Console.Write(x); "; var text2 = @" const string y = x; System.Console.Write(y); "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // const string y = x; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "const").WithLocation(2, 1), // (2,18): error CS0103: The name 'y' does not exist in the current context // const string x = y; Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(2, 18), // (2,18): error CS0103: The name 'x' does not exist in the current context // const string y = x; Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(2, 18) ); comp = CreateCompilation(new[] { "System.Console.WriteLine();", text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // const string x = y; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "const").WithLocation(2, 1), // (2,1): error CS8802: Only one compilation unit can have top-level statements. // const string y = x; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "const").WithLocation(2, 1), // (2,18): error CS0103: The name 'y' does not exist in the current context // const string x = y; Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(2, 18), // (2,18): error CS0103: The name 'x' does not exist in the current context // const string y = x; Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(2, 18) ); } [Fact] public void LocalUsedBeforeDeclaration_02() { var text1 = @" var x = y; System.Console.Write(x); "; var text2 = @" var y = x; System.Console.Write(y); "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // var y = x; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "var").WithLocation(2, 1), // (2,9): error CS0103: The name 'y' does not exist in the current context // var x = y; Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(2, 9), // (2,9): error CS0103: The name 'x' does not exist in the current context // var y = x; Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(2, 9) ); comp = CreateCompilation(new[] { "System.Console.WriteLine();", text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // var x = y; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "var").WithLocation(2, 1), // (2,1): error CS8802: Only one compilation unit can have top-level statements. // var y = x; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "var").WithLocation(2, 1), // (2,9): error CS0103: The name 'y' does not exist in the current context // var x = y; Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(2, 9), // (2,9): error CS0103: The name 'x' does not exist in the current context // var y = x; Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(2, 9) ); } [Fact] public void LocalUsedBeforeDeclaration_03() { var text1 = @" string x = ""x""; System.Console.Write(x); "; var text2 = @" class C1 { void Test() { System.Console.Write(x); } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,30): error CS8801: Cannot use local variable or local function 'x' declared in a top-level statement in this context. // System.Console.Write(x); Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "x").WithArguments("x").WithLocation(6, 30) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree2 = comp.SyntaxTrees[1]; var model2 = comp.GetSemanticModel(tree2); var nameRef = tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Single(); var symbol2 = model2.GetSymbolInfo(nameRef).Symbol; Assert.Equal("System.String x", symbol2.ToTestDisplayString()); Assert.Equal("System.String", model2.GetTypeInfo(nameRef).Type.ToTestDisplayString()); Assert.Null(model2.GetOperation(tree2.GetRoot())); comp = CreateCompilation(new[] { text2, text1 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,30): error CS8801: Cannot use local variable or local function 'x' declared in a top-level statement in this context. // System.Console.Write(x); Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "x").WithArguments("x").WithLocation(6, 30) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel tree2 = comp.SyntaxTrees[0]; model2 = comp.GetSemanticModel(tree2); nameRef = tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Single(); symbol2 = model2.GetSymbolInfo(nameRef).Symbol; Assert.Equal("System.String x", symbol2.ToTestDisplayString()); Assert.Equal("System.String", model2.GetTypeInfo(nameRef).Type.ToTestDisplayString()); Assert.Null(model2.GetOperation(tree2.GetRoot())); } [Fact] public void LocalUsedBeforeDeclaration_04() { var text1 = @" string x = ""x""; local(); "; var text2 = @" void local() { System.Console.Write(x); } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // void local() Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "void").WithLocation(2, 1), // (2,6): warning CS8321: The local function 'local' is declared but never used // void local() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(2, 6), // (2,8): warning CS0219: The variable 'x' is assigned but its value is never used // string x = "x"; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(2, 8), // (3,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(3, 1), // (4,26): error CS0103: The name 'x' does not exist in the current context // System.Console.Write(x); Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(4, 26) ); comp = CreateCompilation(new[] { text2, text1 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // string x = "x"; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "string").WithLocation(2, 1), // (2,6): warning CS8321: The local function 'local' is declared but never used // void local() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(2, 6), // (2,8): warning CS0219: The variable 'x' is assigned but its value is never used // string x = "x"; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(2, 8), // (3,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(3, 1), // (4,26): error CS0103: The name 'x' does not exist in the current context // System.Console.Write(x); Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(4, 26) ); } [Fact] public void FlowAnalysis_01() { var text = @" #nullable enable string a = ""1""; string? b; System.Console.WriteLine(b); string? c = null; c.ToString(); d: System.Console.WriteLine(); string e() => ""1""; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,8): warning CS0219: The variable 'a' is assigned but its value is never used // string a = "1"; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(3, 8), // (5,26): error CS0165: Use of unassigned local variable 'b' // System.Console.WriteLine(b); Diagnostic(ErrorCode.ERR_UseDefViolation, "b").WithArguments("b").WithLocation(5, 26), // (7,1): warning CS8602: Dereference of a possibly null reference. // c.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(7, 1), // (8,1): warning CS0164: This label has not been referenced // d: System.Console.WriteLine(); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(8, 1), // (9,8): warning CS8321: The local function 'e' is declared but never used // string e() => "1"; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "e").WithArguments("e").WithLocation(9, 8) ); var tree = comp.SyntaxTrees.Single(); var reference = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "c").Single(); var model1 = comp.GetSemanticModel(tree); Assert.Equal(CodeAnalysis.NullableFlowState.MaybeNull, model1.GetTypeInfo(reference).Nullability.FlowState); var model2 = comp.GetSemanticModel(tree); Assert.Equal(CodeAnalysis.NullableFlowState.MaybeNull, model1.GetTypeInfo(reference).Nullability.FlowState); } [Fact] public void FlowAnalysis_02() { var text = @" System.Console.WriteLine(); if (args.Length == 0) { return 10; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS0161: '<top-level-statements-entry-point>': not all code paths return a value // System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_ReturnExpected, @"System.Console.WriteLine(); if (args.Length == 0) { return 10; } ").WithArguments("<top-level-statements-entry-point>").WithLocation(2, 1) ); } [Fact] public void NullableRewrite_01() { var text1 = @" void local1() { System.Console.WriteLine(""local1 - "" + s); } "; var text2 = @" using System; string s = ""Hello world!""; foreach (var c in s) { Console.Write(c); } goto label1; label1: Console.WriteLine(); local1(); local2(); "; var text3 = @" void local2() { System.Console.WriteLine(""local2 - "" + s); } "; var comp = CreateCompilation(new[] { text1, text2, text3 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var tree = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree); foreach (var id in tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>()) { _ = model1.GetTypeInfo(id).Nullability; } var model2 = comp.GetSemanticModel(tree); foreach (var id in tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>()) { _ = model2.GetTypeInfo(id).Nullability; } } [Fact] public void Scope_01() { var text = @" using alias1 = Test; string Test = ""1""; System.Console.WriteLine(Test); class Test {} class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 5 Test.ToString(); // 6 Test.EndsWith(null); // 7 _ = nameof(Test); // 8 } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 20), // (34,38): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(34, 38), // (35,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 6 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(35, 13), // (36,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 7 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(36, 13), // (37,24): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 8 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(37, 24) ); var getHashCode = ((Compilation)comp).GetMember("System.Object." + nameof(GetHashCode)); var testType = ((Compilation)comp).GetTypeByMetadataName("Test"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.String Test", declSymbol.ToTestDisplayString()); var names = model1.LookupNames(localDecl.SpanStart); Assert.Contains(getHashCode.Name, names); var symbols = model1.LookupSymbols(localDecl.SpanStart); Assert.Contains(getHashCode, symbols); Assert.Same(getHashCode, model1.LookupSymbols(localDecl.SpanStart, name: getHashCode.Name).Single()); Assert.Contains("Test", names); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: "Test").Single()); symbols = model1.LookupNamespacesAndTypes(localDecl.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupNamespacesAndTypes(localDecl.SpanStart, name: "Test").Single()); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var nameRefs = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test").ToArray(); var nameRef = nameRefs[1]; Assert.Equal("System.Console.WriteLine(Test)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model1, nameRef); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); nameRef = nameRefs[0]; Assert.Equal("using alias1 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); names = model.LookupNames(nameRef.SpanStart); Assert.DoesNotContain(getHashCode.Name, names); Assert.Contains("Test", names); symbols = model.LookupSymbols(nameRef.SpanStart); Assert.DoesNotContain(getHashCode, symbols); Assert.Empty(model.LookupSymbols(nameRef.SpanStart, name: getHashCode.Name)); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); nameRef = nameRefs[2]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); Assert.DoesNotContain(getHashCode.Name, model.LookupNames(nameRef.SpanStart)); verifyModel(declSymbol, model, nameRef); nameRef = nameRefs[4]; Assert.Equal("System.Console.WriteLine(Test)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model, nameRef); nameRef = nameRefs[8]; Assert.Equal("using alias2 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model, nameRef); nameRef = nameRefs[9]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); Assert.DoesNotContain(getHashCode.Name, model.LookupNames(nameRef.SpanStart)); verifyModel(declSymbol, model, nameRef); nameRef = nameRefs[11]; Assert.Equal("System.Console.WriteLine(Test)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model, nameRef); void verifyModel(ISymbol declSymbol, SemanticModel model, IdentifierNameSyntax nameRef) { var names = model.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); var symbols = model.LookupSymbols(nameRef.SpanStart); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); symbols = model.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model.LookupNamespacesAndTypes(nameRef.SpanStart, name: "Test").Single()); } } [Fact] public void Scope_02() { var text1 = @" string Test = ""1""; System.Console.WriteLine(Test); "; var text2 = @" using alias1 = Test; class Test {} class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 5 Test.ToString(); // 6 Test.EndsWith(null); // 7 _ = nameof(Test); // 8 } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 20), // (31,38): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(31, 38), // (32,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 6 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(32, 13), // (33,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 7 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(33, 13), // (34,24): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 8 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(34, 24) ); var getHashCode = ((Compilation)comp).GetMember("System.Object." + nameof(GetHashCode)); var testType = ((Compilation)comp).GetTypeByMetadataName("Test"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.String Test", declSymbol.ToTestDisplayString()); var names = model1.LookupNames(localDecl.SpanStart); Assert.Contains(getHashCode.Name, names); var symbols = model1.LookupSymbols(localDecl.SpanStart); Assert.Contains(getHashCode, symbols); Assert.Same(getHashCode, model1.LookupSymbols(localDecl.SpanStart, name: getHashCode.Name).Single()); Assert.Contains("Test", names); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: "Test").Single()); symbols = model1.LookupNamespacesAndTypes(localDecl.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupNamespacesAndTypes(localDecl.SpanStart, name: "Test").Single()); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree2 = comp.SyntaxTrees[1]; var model2 = comp.GetSemanticModel(tree2); Assert.Null(model2.GetDeclaredSymbol((CompilationUnitSyntax)tree2.GetRoot())); var nameRefs = tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test").ToArray(); var nameRef = nameRefs[0]; Assert.Equal("using alias1 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); names = model2.LookupNames(nameRef.SpanStart); Assert.DoesNotContain(getHashCode.Name, names); Assert.Contains("Test", names); symbols = model2.LookupSymbols(nameRef.SpanStart); Assert.DoesNotContain(getHashCode, symbols); Assert.Empty(model2.LookupSymbols(nameRef.SpanStart, name: getHashCode.Name)); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model2.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); nameRef = nameRefs[1]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); Assert.DoesNotContain(getHashCode.Name, model2.LookupNames(nameRef.SpanStart)); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[3]; Assert.Equal("System.Console.WriteLine(Test)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[7]; Assert.Equal("using alias2 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[8]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); Assert.DoesNotContain(getHashCode.Name, model2.LookupNames(nameRef.SpanStart)); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[10]; Assert.Equal("System.Console.WriteLine(Test)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); void verifyModel(ISymbol declSymbol, SemanticModel model2, IdentifierNameSyntax nameRef) { var names = model2.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); var symbols = model2.LookupSymbols(nameRef.SpanStart); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model2.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); symbols = model2.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model2.LookupNamespacesAndTypes(nameRef.SpanStart, name: "Test").Single()); } } [Fact] public void Scope_03() { var text1 = @" string Test = ""1""; System.Console.WriteLine(Test); "; var text2 = @" class Test {} class Derived : Test { void M() { int Test = 0; System.Console.WriteLine(Test++); } } namespace N1 { class Derived : Test { void M() { int Test = 1; System.Console.WriteLine(Test++); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); comp = CreateCompilation(text1 + text2, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); Assert.Throws<System.ArgumentException>(() => CreateCompilation(new[] { Parse(text1, filename: "text1", DefaultParseOptions), Parse(text1, filename: "text2", TestOptions.Regular6) }, options: TestOptions.DebugExe)); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics( // (2,1): error CS8107: Feature 'top-level statements' is not available in C# 7.0. Please use language version 9.0 or greater. // string Test = "1"; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, @"string Test = ""1"";").WithArguments("top-level statements", "9.0").WithLocation(2, 1) ); } [Fact] public void Scope_04() { var text = @" using alias1 = Test; string Test() => ""1""; System.Console.WriteLine(Test()); class Test {} class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 6 Test().ToString(); // 7 Test().EndsWith(null); // 8 var d = new System.Func<string>(Test); // 9 d(); _ = nameof(Test); // 10 } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 33), // (21,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(21, 20), // (36,38): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 6 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(36, 38), // (37,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 7 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(37, 13), // (38,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 8 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(38, 13), // (39,45): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // var d = new System.Func<string>(Test); // 9 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(39, 45), // (41,24): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 10 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(41, 24) ); var testType = ((Compilation)comp).GetTypeByMetadataName("Test"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.String Test()", declSymbol.ToTestDisplayString()); var names = model1.LookupNames(localDecl.SpanStart); var symbols = model1.LookupSymbols(localDecl.SpanStart); Assert.Contains("Test", names); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: "Test").Single()); symbols = model1.LookupNamespacesAndTypes(localDecl.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupNamespacesAndTypes(localDecl.SpanStart, name: "Test").Single()); var nameRefs = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test").ToArray(); var nameRef = nameRefs[0]; Assert.Equal("using alias1 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); names = model1.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); symbols = model1.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); nameRef = nameRefs[2]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model1, nameRef); nameRef = nameRefs[4]; Assert.Equal("System.Console.WriteLine(Test())", nameRef.Parent.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model1, nameRef); nameRef = nameRefs[9]; Assert.Equal("using alias2 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model1, nameRef); nameRef = nameRefs[10]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model1, nameRef); nameRef = nameRefs[12]; Assert.Equal("System.Console.WriteLine(Test())", nameRef.Parent.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model1, nameRef); void verifyModel(ISymbol declSymbol, SemanticModel model2, IdentifierNameSyntax nameRef) { var names = model2.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); var symbols = model2.LookupSymbols(nameRef.SpanStart); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model2.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); symbols = model2.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model2.LookupNamespacesAndTypes(nameRef.SpanStart, name: "Test").Single()); } } [Fact] public void Scope_05() { var text1 = @" string Test() => ""1""; System.Console.WriteLine(Test()); "; var text2 = @" using alias1 = Test; class Test {} class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 6 Test().ToString(); // 7 Test().EndsWith(null); // 8 var d = new System.Func<string>(Test); // 9 d(); _ = nameof(Test); // 10 } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 33), // (18,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 20), // (33,38): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 6 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(33, 38), // (34,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 7 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(34, 13), // (35,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 8 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(35, 13), // (36,45): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // var d = new System.Func<string>(Test); // 9 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(36, 45), // (38,24): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 10 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(38, 24) ); var testType = ((Compilation)comp).GetTypeByMetadataName("Test"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.String Test()", declSymbol.ToTestDisplayString()); var names = model1.LookupNames(localDecl.SpanStart); var symbols = model1.LookupSymbols(localDecl.SpanStart); Assert.Contains("Test", names); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: "Test").Single()); symbols = model1.LookupNamespacesAndTypes(localDecl.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupNamespacesAndTypes(localDecl.SpanStart, name: "Test").Single()); var tree2 = comp.SyntaxTrees[1]; var model2 = comp.GetSemanticModel(tree2); var nameRefs = tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test").ToArray(); var nameRef = nameRefs[0]; Assert.Equal("using alias1 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); names = model2.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); symbols = model2.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model2.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); nameRef = nameRefs[1]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[3]; Assert.Equal("System.Console.WriteLine(Test())", nameRef.Parent.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[8]; Assert.Equal("using alias2 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[9]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[11]; Assert.Equal("System.Console.WriteLine(Test())", nameRef.Parent.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); void verifyModel(ISymbol declSymbol, SemanticModel model2, IdentifierNameSyntax nameRef) { var names = model2.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); var symbols = model2.LookupSymbols(nameRef.SpanStart); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model2.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); symbols = model2.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model2.LookupNamespacesAndTypes(nameRef.SpanStart, name: "Test").Single()); } } [Fact] public void Scope_06() { var text1 = @" string Test() => ""1""; System.Console.WriteLine(Test()); "; var text2 = @" class Test {} class Derived : Test { void M() { int Test() => 1; int x = Test() + 1; System.Console.WriteLine(x); } } namespace N1 { class Derived : Test { void M() { int Test() => 1; int x = Test() + 1; System.Console.WriteLine(x); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); comp = CreateCompilation(text1 + text2, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics( // (2,1): error CS8107: Feature 'top-level statements' is not available in C# 7.0. Please use language version 9.0 or greater. // string Test() => "1"; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, @"string Test() => ""1"";").WithArguments("top-level statements", "9.0").WithLocation(2, 1) ); } [Fact] public void Scope_07() { var text = @" using alias1 = Test; goto Test; Test: System.Console.WriteLine(""1""); class Test {} class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); goto Test; // 1 } } namespace N1 { using alias2 = Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); goto Test; // 2 } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (15,14): error CS0159: No such label 'Test' within the scope of the goto statement // goto Test; // 1 Diagnostic(ErrorCode.ERR_LabelNotFound, "Test").WithArguments("Test").WithLocation(15, 14), // (30,18): error CS0159: No such label 'Test' within the scope of the goto statement // goto Test; // 2 Diagnostic(ErrorCode.ERR_LabelNotFound, "Test").WithArguments("Test").WithLocation(30, 18) ); var testType = ((Compilation)comp).GetTypeByMetadataName("Test"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var labelDecl = tree1.GetRoot().DescendantNodes().OfType<LabeledStatementSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(labelDecl); Assert.Equal("Test", declSymbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Label, declSymbol.Kind); var names = model1.LookupNames(labelDecl.SpanStart); var symbols = model1.LookupSymbols(labelDecl.SpanStart); Assert.Contains("Test", names); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupSymbols(labelDecl.SpanStart, name: "Test").Single()); symbols = model1.LookupNamespacesAndTypes(labelDecl.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupNamespacesAndTypes(labelDecl.SpanStart, name: "Test").Single()); Assert.Same(declSymbol, model1.LookupLabels(labelDecl.SpanStart).Single()); Assert.Same(declSymbol, model1.LookupLabels(labelDecl.SpanStart, name: "Test").Single()); var nameRefs = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test").ToArray(); var nameRef = nameRefs[0]; Assert.Equal("using alias1 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); names = model1.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); symbols = model1.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); Assert.Empty(model1.LookupLabels(nameRef.SpanStart)); Assert.Empty(model1.LookupLabels(nameRef.SpanStart, name: "Test")); nameRef = nameRefs[1]; Assert.Equal("goto Test;", nameRef.Parent.ToString()); Assert.Same(declSymbol, model1.GetSymbolInfo(nameRef).Symbol); names = model1.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); symbols = model1.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); Assert.Same(declSymbol, model1.LookupLabels(nameRef.SpanStart).Single()); Assert.Same(declSymbol, model1.LookupLabels(nameRef.SpanStart, name: "Test").Single()); nameRef = nameRefs[2]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(model1, nameRef); nameRef = nameRefs[4]; Assert.Equal("goto Test;", nameRef.Parent.ToString()); Assert.Null(model1.GetSymbolInfo(nameRef).Symbol); verifyModel(model1, nameRef); nameRef = nameRefs[5]; Assert.Equal("using alias2 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(model1, nameRef); nameRef = nameRefs[6]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(model1, nameRef); nameRef = nameRefs[8]; Assert.Null(model1.GetSymbolInfo(nameRef).Symbol); Assert.Equal("goto Test;", nameRef.Parent.ToString()); verifyModel(model1, nameRef); void verifyModel(SemanticModel model2, IdentifierNameSyntax nameRef) { var names = model2.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); var symbols = model2.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model2.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); symbols = model2.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model2.LookupNamespacesAndTypes(nameRef.SpanStart, name: "Test").Single()); Assert.Empty(model2.LookupLabels(nameRef.SpanStart)); Assert.Empty(model2.LookupLabels(nameRef.SpanStart, name: "Test")); } } [Fact] public void Scope_08() { var text = @" goto Test; Test: System.Console.WriteLine(""1""); class Test {} class Derived : Test { void M() { goto Test; Test: System.Console.WriteLine(); } } namespace N1 { class Derived : Test { void M() { goto Test; Test: System.Console.WriteLine(); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); } [Fact] public void Scope_09() { var text = @" string Test = ""1""; System.Console.WriteLine(Test); new void M() { int Test = 0; System.Console.WriteLine(Test++); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (5,10): error CS0116: A namespace cannot directly contain members such as fields or methods // new void M() Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "M").WithLocation(5, 10), // (5,10): warning CS0109: The member '<invalid-global-code>.M()' does not hide an accessible member. The new keyword is not required. // new void M() Diagnostic(ErrorCode.WRN_NewNotRequired, "M").WithArguments("<invalid-global-code>.M()").WithLocation(5, 10) ); } [Fact] public void Scope_10() { var text = @" string Test = ""1""; System.Console.WriteLine(Test); new int F = C1.GetInt(out var Test); class C1 { public static int GetInt(out int v) { v = 1; return v; } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (5,9): error CS0116: A namespace cannot directly contain members such as fields or methods // new int F = C1.GetInt(out var Test); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "F").WithLocation(5, 9), // (5,9): warning CS0109: The member '<invalid-global-code>.F' does not hide an accessible member. The new keyword is not required. // new int F = C1.GetInt(out var Test); Diagnostic(ErrorCode.WRN_NewNotRequired, "F").WithArguments("<invalid-global-code>.F").WithLocation(5, 9) ); } [Fact] public void Scope_11() { var text = @" goto Test; Test: System.Console.WriteLine(); new void M() { goto Test; Test: System.Console.WriteLine(); }"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (5,10): error CS0116: A namespace cannot directly contain members such as fields or methods // new void M() Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "M").WithLocation(5, 10), // (5,10): warning CS0109: The member '<invalid-global-code>.M()' does not hide an accessible member. The new keyword is not required. // new void M() Diagnostic(ErrorCode.WRN_NewNotRequired, "M").WithArguments("<invalid-global-code>.M()").WithLocation(5, 10) ); } [Fact] public void Scope_12() { var text = @" using alias1 = Test; string Test() => ""1""; System.Console.WriteLine(Test()); class Test {} struct Derived { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; struct Derived { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 6 Test().ToString(); // 7 Test().EndsWith(null); // 8 var d = new System.Func<string>(Test); // 9 d(); _ = nameof(Test); // 10 } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 33), // (21,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(21, 20), // (36,38): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 6 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(36, 38), // (37,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 7 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(37, 13), // (38,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 8 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(38, 13), // (39,45): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // var d = new System.Func<string>(Test); // 9 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(39, 45), // (41,24): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 10 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(41, 24) ); } [Fact] public void Scope_13() { var text = @" using alias1 = Test; string Test() => ""1""; System.Console.WriteLine(Test()); class Test {} interface Derived { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; interface Derived { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 6 Test().ToString(); // 7 Test().EndsWith(null); // 8 var d = new System.Func<string>(Test); // 9 d(); _ = nameof(Test); // 10 } } } "; var comp = CreateCompilation(text, targetFramework: TargetFramework.NetCoreApp, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 33), // (21,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(21, 20), // (36,38): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 6 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(36, 38), // (37,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 7 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(37, 13), // (38,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 8 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(38, 13), // (39,45): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // var d = new System.Func<string>(Test); // 9 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(39, 45), // (41,24): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 10 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(41, 24) ); } [Fact] public void Scope_14() { var text = @" using alias1 = Test; string Test() => ""1""; System.Console.WriteLine(Test()); class Test {} delegate Test D(alias1 x); namespace N1 { using alias2 = Test; delegate Test D(alias2 x); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); } [Fact] public void Scope_15() { var text = @" const int Test = 1; System.Console.WriteLine(Test); class Test {} enum E1 { T = Test, } namespace N1 { enum E1 { T = Test, } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (9,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // T = Test, Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(9, 9), // (16,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // T = Test, Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 13) ); } [Fact] public void Scope_16() { var text1 = @" using alias1 = System.String; alias1 x = ""1""; alias2 y = ""1""; System.Console.WriteLine(x); System.Console.WriteLine(y); local(); "; var text2 = @" using alias2 = System.String; void local() { alias1 a = ""2""; alias2 b = ""2""; System.Console.WriteLine(a); System.Console.WriteLine(b); } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,1): error CS8802: Only one compilation unit can have top-level statements. // void local() Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "void").WithLocation(3, 1), // (3,6): warning CS8321: The local function 'local' is declared but never used // void local() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(3, 6), // (4,1): error CS0246: The type or namespace name 'alias2' could not be found (are you missing a using directive or an assembly reference?) // alias2 y = "1"; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias2").WithArguments("alias2").WithLocation(4, 1), // (5,5): error CS0246: The type or namespace name 'alias1' could not be found (are you missing a using directive or an assembly reference?) // alias1 a = "2"; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias1").WithArguments("alias1").WithLocation(5, 5), // (7,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(7, 1) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var nameRef = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "alias1" && !id.Parent.IsKind(SyntaxKind.NameEquals)).Single(); Assert.NotEmpty(model1.LookupNamespacesAndTypes(nameRef.SpanStart, name: "alias1")); Assert.Empty(model1.LookupNamespacesAndTypes(nameRef.SpanStart, name: "alias2")); nameRef = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "alias2").Single(); model1.GetDiagnostics(nameRef.Ancestors().OfType<StatementSyntax>().First().Span).Verify( // (4,1): error CS0246: The type or namespace name 'alias2' could not be found (are you missing a using directive or an assembly reference?) // alias2 y = "1"; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias2").WithArguments("alias2").WithLocation(4, 1) ); model1.GetDiagnostics().Verify( // (4,1): error CS0246: The type or namespace name 'alias2' could not be found (are you missing a using directive or an assembly reference?) // alias2 y = "1"; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias2").WithArguments("alias2").WithLocation(4, 1), // (7,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(7, 1) ); var tree2 = comp.SyntaxTrees[1]; var model2 = comp.GetSemanticModel(tree2); nameRef = tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "alias2" && !id.Parent.IsKind(SyntaxKind.NameEquals)).Single(); Assert.Empty(model2.LookupNamespacesAndTypes(nameRef.SpanStart, name: "alias1")); Assert.NotEmpty(model2.LookupNamespacesAndTypes(nameRef.SpanStart, name: "alias2")); nameRef = tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "alias1").Single(); model2.GetDiagnostics(nameRef.Ancestors().OfType<StatementSyntax>().First().Span).Verify( // (5,5): error CS0246: The type or namespace name 'alias1' could not be found (are you missing a using directive or an assembly reference?) // alias1 a = "2"; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias1").WithArguments("alias1").WithLocation(5, 5) ); model2.GetDiagnostics().Verify( // (3,1): error CS8802: Only one compilation unit can have top-level statements. // void local() Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "void").WithLocation(3, 1), // (3,6): warning CS8321: The local function 'local' is declared but never used // void local() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(3, 6), // (5,5): error CS0246: The type or namespace name 'alias1' could not be found (are you missing a using directive or an assembly reference?) // alias1 a = "2"; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias1").WithArguments("alias1").WithLocation(5, 5) ); } [Fact] public void Scope_17() { var text = @" using alias1 = N2.Test; using N2; string Test = ""1""; System.Console.WriteLine(Test); namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; using N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 20) ); } [Fact] public void Scope_18() { var text1 = @" string Test = ""1""; System.Console.WriteLine(Test); "; var text2 = @" using alias1 = N2.Test; using N2; namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; using N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 20) ); } [Fact] public void Scope_19() { var text = @" using alias1 = N2.Test; using N2; string Test() => ""1""; System.Console.WriteLine(Test()); namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; using N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 33), // (21,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(21, 20) ); } [Fact] public void Scope_20() { var text1 = @" string Test() => ""1""; System.Console.WriteLine(Test()); "; var text2 = @" using alias1 = N2.Test; using N2; namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; using N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 33), // (18,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 20) ); } [Fact] public void Scope_21() { var text = @" using Test = N2.Test; string Test = ""1""; System.Console.WriteLine(Test); namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; System.Console.WriteLine(x); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; using Test = N2.Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 20) ); } [Fact] public void Scope_22() { var text1 = @" string Test = ""1""; System.Console.WriteLine(Test); "; var text2 = @" using Test = N2.Test; namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; System.Console.WriteLine(x); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; using Test = N2.Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 20) ); } [Fact] public void Scope_23() { var text = @" using Test = N2.Test; string Test() => ""1""; System.Console.WriteLine(Test()); namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; System.Console.WriteLine(x); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; using Test = N2.Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 33), // (21,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(21, 20) ); } [Fact] public void Scope_24() { var text1 = @" string Test() => ""1""; System.Console.WriteLine(Test()); "; var text2 = @" using Test = N2.Test; namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; System.Console.WriteLine(x); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; using Test = N2.Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 33), // (18,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 20) ); } [Fact] public void Scope_25() { var text = @" using alias1 = N2.Test; using static N2; string Test = ""1""; System.Console.WriteLine(Test); class N2 { public class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; using static N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 20) ); } [Fact] public void Scope_26() { var text1 = @" string Test = ""1""; System.Console.WriteLine(Test); "; var text2 = @" using alias1 = N2.Test; using static N2; class N2 { public class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; using static N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 20) ); } [Fact] public void Scope_27() { var text = @" using alias1 = N2.Test; using static N2; string Test() => ""1""; System.Console.WriteLine(Test()); class N2 { public class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; using static N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 33), // (21,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(21, 20) ); } [Fact] public void Scope_28() { var text1 = @" string Test() => ""1""; System.Console.WriteLine(Test()); "; var text2 = @" using alias1 = N2.Test; using static N2; class N2 { public class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; using static N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 33), // (18,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 20) ); } [Fact] public void Scope_29() { var text = @" using static N2; string Test() => ""1""; System.Console.WriteLine(Test()); class N2 { public static string Test() => null; } class Derived { void M() { System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using static N2; class Derived { void M() { System.Console.WriteLine(Test()); Test().ToString(); Test().EndsWith(null); var d = new System.Func<string>(Test); d(); _ = nameof(Test); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): hidden CS8019: Unnecessary using directive. // using static N2; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static N2;").WithLocation(2, 1), // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 33), // (18,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 20) ); } [Fact] public void Scope_30() { var text1 = @" string Test() => ""1""; System.Console.WriteLine(Test()); "; var text2 = @" using static N2; class N2 { public static string Test() => null; } class Derived { void M() { System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using static N2; class Derived { void M() { System.Console.WriteLine(Test()); Test().ToString(); Test().EndsWith(null); var d = new System.Func<string>(Test); d(); _ = nameof(Test); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): hidden CS8019: Unnecessary using directive. // using static N2; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static N2;").WithLocation(2, 1), // (10,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(10, 34), // (11,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(11, 9), // (12,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(12, 9), // (13,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 33), // (15,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 20) ); } [Fact] public void Scope_31() { var text = @" using alias1 = args; System.Console.WriteLine(args); class args {} class Derived : args { void M() { args x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(args); // 1 args.ToString(); // 2 args[0].EndsWith(null); // 3 _ = nameof(args); } } namespace N1 { using alias2 = args; class Derived : args { void M() { args x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(args); // 4 args.ToString(); // 5 args[0].EndsWith(null); // 6 _ = nameof(args); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (15,34): error CS0119: 'args' is a type, which is not valid in the given context // System.Console.WriteLine(args); // 1 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(15, 34), // (16,9): error CS0120: An object reference is required for the non-static field, method, or property 'object.ToString()' // args.ToString(); // 2 Diagnostic(ErrorCode.ERR_ObjectRequired, "args.ToString").WithArguments("object.ToString()").WithLocation(16, 9), // (17,9): error CS0119: 'args' is a type, which is not valid in the given context // args[0].EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(17, 9), // (33,38): error CS0119: 'args' is a type, which is not valid in the given context // System.Console.WriteLine(args); // 4 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(33, 38), // (34,13): error CS0120: An object reference is required for the non-static field, method, or property 'object.ToString()' // args.ToString(); // 5 Diagnostic(ErrorCode.ERR_ObjectRequired, "args.ToString").WithArguments("object.ToString()").WithLocation(34, 13), // (35,13): error CS0119: 'args' is a type, which is not valid in the given context // args[0].EndsWith(null); // 6 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(35, 13) ); var testType = ((Compilation)comp).GetTypeByMetadataName("args"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var nameRefs = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "args").ToArray(); var nameRef = nameRefs[0]; Assert.Equal("using alias1 = args;", nameRef.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); var names = model.LookupNames(nameRef.SpanStart); Assert.Contains("args", names); var symbols = model.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.False(symbols.Any(s => s.Kind == SymbolKind.Parameter)); Assert.Same(testType, model.LookupSymbols(nameRef.SpanStart, name: "args").Single()); nameRef = nameRefs[1]; Assert.Equal("System.Console.WriteLine(args)", nameRef.Parent.Parent.Parent.ToString()); var parameter = model.GetSymbolInfo(nameRef).Symbol; Assert.Equal("System.String[] args", parameter.ToTestDisplayString()); Assert.Equal("<top-level-statements-entry-point>", parameter.ContainingSymbol.ToTestDisplayString()); names = model.LookupNames(nameRef.SpanStart); Assert.Contains("args", names); symbols = model.LookupSymbols(nameRef.SpanStart); Assert.DoesNotContain(testType, symbols); Assert.Contains(parameter, symbols); Assert.Same(parameter, model.LookupSymbols(nameRef.SpanStart, name: "args").Single()); symbols = model.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(parameter, symbols); Assert.Same(testType, model.LookupNamespacesAndTypes(nameRef.SpanStart, name: "args").Single()); nameRef = nameRefs[2]; Assert.Equal(": args", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(parameter, model, nameRef); nameRef = nameRefs[4]; Assert.Equal("System.Console.WriteLine(args)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(parameter, model, nameRef); nameRef = nameRefs[8]; Assert.Equal("using alias2 = args;", nameRef.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(parameter, model, nameRef); nameRef = nameRefs[9]; Assert.Equal(": args", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(parameter, model, nameRef); nameRef = nameRefs[11]; Assert.Equal("System.Console.WriteLine(args)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(parameter, model, nameRef); void verifyModel(ISymbol declSymbol, SemanticModel model, IdentifierNameSyntax nameRef) { var names = model.LookupNames(nameRef.SpanStart); Assert.Contains("args", names); var symbols = model.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model.LookupSymbols(nameRef.SpanStart, name: "args").Single()); symbols = model.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model.LookupNamespacesAndTypes(nameRef.SpanStart, name: "args").Single()); } } [Fact] public void Scope_32() { var text1 = @" System.Console.WriteLine(args); "; var text2 = @" using alias1 = args; class args {} class Derived : args { void M() { args x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(args); // 1 args.ToString(); // 2 args[0].EndsWith(null); // 3 _ = nameof(args); } } namespace N1 { using alias2 = args; class Derived : args { void M() { args x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(args); // 4 args.ToString(); // 5 args[0].EndsWith(null); // 6 _ = nameof(args); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS0119: 'args' is a type, which is not valid in the given context // System.Console.WriteLine(args); // 1 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(13, 34), // (14,9): error CS0120: An object reference is required for the non-static field, method, or property 'object.ToString()' // args.ToString(); // 2 Diagnostic(ErrorCode.ERR_ObjectRequired, "args.ToString").WithArguments("object.ToString()").WithLocation(14, 9), // (15,9): error CS0119: 'args' is a type, which is not valid in the given context // args[0].EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(15, 9), // (31,38): error CS0119: 'args' is a type, which is not valid in the given context // System.Console.WriteLine(args); // 4 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(31, 38), // (32,13): error CS0120: An object reference is required for the non-static field, method, or property 'object.ToString()' // args.ToString(); // 5 Diagnostic(ErrorCode.ERR_ObjectRequired, "args.ToString").WithArguments("object.ToString()").WithLocation(32, 13), // (33,13): error CS0119: 'args' is a type, which is not valid in the given context // args[0].EndsWith(null); // 6 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(33, 13) ); var testType = ((Compilation)comp).GetTypeByMetadataName("args"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree = comp.SyntaxTrees[1]; var model = comp.GetSemanticModel(tree); var nameRefs = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "args").ToArray(); var nameRef = nameRefs[0]; Assert.Equal("using alias1 = args;", nameRef.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); var names = model.LookupNames(nameRef.SpanStart); Assert.Contains("args", names); var symbols = model.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.False(symbols.Any(s => s.Kind == SymbolKind.Parameter)); Assert.Same(testType, model.LookupSymbols(nameRef.SpanStart, name: "args").Single()); nameRef = nameRefs[1]; Assert.Equal(": args", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(model, nameRef); nameRef = nameRefs[3]; Assert.Equal("System.Console.WriteLine(args)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(model, nameRef); nameRef = nameRefs[7]; Assert.Equal("using alias2 = args;", nameRef.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(model, nameRef); nameRef = nameRefs[8]; Assert.Equal(": args", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(model, nameRef); nameRef = nameRefs[10]; Assert.Equal("System.Console.WriteLine(args)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(model, nameRef); void verifyModel(SemanticModel model, IdentifierNameSyntax nameRef) { var names = model.LookupNames(nameRef.SpanStart); Assert.Contains("args", names); var symbols = model.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.False(symbols.Any(s => s.Kind == SymbolKind.Parameter)); Assert.Same(testType, model.LookupSymbols(nameRef.SpanStart, name: "args").Single()); symbols = model.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.False(symbols.Any(s => s.Kind == SymbolKind.Parameter)); Assert.Same(testType, model.LookupNamespacesAndTypes(nameRef.SpanStart, name: "args").Single()); } } [Fact] public void Scope_33() { var text = @" System.Console.WriteLine(args); class Test { void M() { System.Console.WriteLine(args); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (8,34): error CS0103: The name 'args' does not exist in the current context // System.Console.WriteLine(args); Diagnostic(ErrorCode.ERR_NameNotInContext, "args").WithArguments("args").WithLocation(8, 34) ); } [Fact] public void Scope_34() { var text1 = @" System.Console.WriteLine(args); "; var text2 = @" class Test { void M() { System.Console.WriteLine(args); } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,34): error CS0103: The name 'args' does not exist in the current context // System.Console.WriteLine(args); Diagnostic(ErrorCode.ERR_NameNotInContext, "args").WithArguments("args").WithLocation(6, 34) ); } [Fact] public void LocalFunctionStatement_01() { var text = @" local(); void local() { System.Console.WriteLine(15); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "15"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single(); var reference = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "local").Single(); var local = model.GetDeclaredSymbol(declarator); Assert.Same(local, model.GetSymbolInfo(reference).Symbol); Assert.Equal("void local()", local.ToTestDisplayString()); Assert.Equal(MethodKind.LocalFunction, ((IMethodSymbol)local).MethodKind); Assert.Equal(SymbolKind.Method, local.ContainingSymbol.Kind); Assert.False(local.ContainingSymbol.IsImplicitlyDeclared); Assert.Equal(SymbolKind.NamedType, local.ContainingSymbol.ContainingSymbol.Kind); Assert.False(local.ContainingSymbol.ContainingSymbol.IsImplicitlyDeclared); Assert.True(((INamespaceSymbol)local.ContainingSymbol.ContainingSymbol.ContainingSymbol).IsGlobalNamespace); VerifyFlowGraph(comp, tree.GetRoot(), @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Methods: [void local()] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'local();') Expression: IInvocationOperation (void local()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'local()') Instance Receiver: null Arguments(0) Next (Regular) Block[B2] Leaving: {R1} { void local() Block[B0#0R1] - Entry Statements (0) Next (Regular) Block[B1#0R1] Block[B1#0R1] - Block Predecessors: [B0#0R1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... teLine(15);') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... iteLine(15)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '15') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 15) (Syntax: '15') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B2#0R1] Block[B2#0R1] - Exit Predecessors: [B1#0R1] Statements (0) } } Block[B2] - Exit Predecessors: [B1] Statements (0) "); } [Fact] public void LocalFunctionStatement_02() { var text = @" local(); void local() => System.Console.WriteLine(""Hi!""); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void LocalFunctionStatement_03() { var text = @" local(); void I1.local() { System.Console.WriteLine(""Hi!""); } interface I1 { void local(); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(2, 1), // (4,6): error CS0540: '<invalid-global-code>.I1.local()': containing type does not implement interface 'I1' // void I1.local() Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1").WithArguments("<invalid-global-code>.I1.local()", "I1").WithLocation(4, 6), // (4,9): error CS0116: A namespace cannot directly contain members such as fields or methods // void I1.local() Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "local").WithLocation(4, 9) ); } [Fact] public void LocalFunctionStatement_04() { var text = @" new void localA() => System.Console.WriteLine(); localA(); public void localB() => System.Console.WriteLine(); localB(); virtual void localC() => System.Console.WriteLine(); localC(); sealed void localD() => System.Console.WriteLine(); localD(); override void localE() => System.Console.WriteLine(); localE(); abstract void localF() => System.Console.WriteLine(); localF(); partial void localG() => System.Console.WriteLine(); localG(); extern void localH() => System.Console.WriteLine(); localH(); [System.Obsolete()] void localI() => System.Console.WriteLine(); localI(); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,10): error CS0116: A namespace cannot directly contain members such as fields or methods // new void localA() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "localA").WithLocation(2, 10), // (2,10): warning CS0109: The member '<invalid-global-code>.localA()' does not hide an accessible member. The new keyword is not required. // new void localA() => System.Console.WriteLine(); Diagnostic(ErrorCode.WRN_NewNotRequired, "localA").WithArguments("<invalid-global-code>.localA()").WithLocation(2, 10), // (3,1): error CS0103: The name 'localA' does not exist in the current context // localA(); Diagnostic(ErrorCode.ERR_NameNotInContext, "localA").WithArguments("localA").WithLocation(3, 1), // (4,1): error CS0106: The modifier 'public' is not valid for this item // public void localB() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "public").WithArguments("public").WithLocation(4, 1), // (6,14): error CS0116: A namespace cannot directly contain members such as fields or methods // virtual void localC() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "localC").WithLocation(6, 14), // (6,14): error CS0621: '<invalid-global-code>.localC()': virtual or abstract members cannot be private // virtual void localC() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_VirtualPrivate, "localC").WithArguments("<invalid-global-code>.localC()").WithLocation(6, 14), // (7,1): error CS0103: The name 'localC' does not exist in the current context // localC(); Diagnostic(ErrorCode.ERR_NameNotInContext, "localC").WithArguments("localC").WithLocation(7, 1), // (8,13): error CS0116: A namespace cannot directly contain members such as fields or methods // sealed void localD() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "localD").WithLocation(8, 13), // (8,13): error CS0238: '<invalid-global-code>.localD()' cannot be sealed because it is not an override // sealed void localD() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_SealedNonOverride, "localD").WithArguments("<invalid-global-code>.localD()").WithLocation(8, 13), // (9,1): error CS0103: The name 'localD' does not exist in the current context // localD(); Diagnostic(ErrorCode.ERR_NameNotInContext, "localD").WithArguments("localD").WithLocation(9, 1), // (10,15): error CS0116: A namespace cannot directly contain members such as fields or methods // override void localE() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "localE").WithLocation(10, 15), // (10,15): error CS0621: '<invalid-global-code>.localE()': virtual or abstract members cannot be private // override void localE() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_VirtualPrivate, "localE").WithArguments("<invalid-global-code>.localE()").WithLocation(10, 15), // (10,15): error CS0115: '<invalid-global-code>.localE()': no suitable method found to override // override void localE() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_OverrideNotExpected, "localE").WithArguments("<invalid-global-code>.localE()").WithLocation(10, 15), // (11,1): error CS0103: The name 'localE' does not exist in the current context // localE(); Diagnostic(ErrorCode.ERR_NameNotInContext, "localE").WithArguments("localE").WithLocation(11, 1), // (12,15): error CS0116: A namespace cannot directly contain members such as fields or methods // abstract void localF() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "localF").WithLocation(12, 15), // (12,15): error CS0500: '<invalid-global-code>.localF()' cannot declare a body because it is marked abstract // abstract void localF() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_AbstractHasBody, "localF").WithArguments("<invalid-global-code>.localF()").WithLocation(12, 15), // (12,15): error CS0621: '<invalid-global-code>.localF()': virtual or abstract members cannot be private // abstract void localF() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_VirtualPrivate, "localF").WithArguments("<invalid-global-code>.localF()").WithLocation(12, 15), // (13,1): error CS0103: The name 'localF' does not exist in the current context // localF(); Diagnostic(ErrorCode.ERR_NameNotInContext, "localF").WithArguments("localF").WithLocation(13, 1), // (14,14): error CS0116: A namespace cannot directly contain members such as fields or methods // partial void localG() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "localG").WithLocation(14, 14), // (14,14): error CS0759: No defining declaration found for implementing declaration of partial method '<invalid-global-code>.localG()' // partial void localG() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "localG").WithArguments("<invalid-global-code>.localG()").WithLocation(14, 14), // (14,14): error CS0751: A partial method must be declared within a partial type // partial void localG() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_PartialMethodOnlyInPartialClass, "localG").WithLocation(14, 14), // (15,1): error CS0103: The name 'localG' does not exist in the current context // localG(); Diagnostic(ErrorCode.ERR_NameNotInContext, "localG").WithArguments("localG").WithLocation(15, 1), // (16,13): error CS0179: 'localH()' cannot be extern and declare a body // extern void localH() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_ExternHasBody, "localH").WithArguments("localH()").WithLocation(16, 13), // (20,1): warning CS0612: 'localI()' is obsolete // localI(); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "localI()").WithArguments("localI()").WithLocation(20, 1) ); } [Fact] public void LocalFunctionStatement_05() { var text = @" void local1() => System.Console.Write(""1""); local1(); void local2() => System.Console.Write(""2""); local2(); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "12"); } [Fact] public void LocalFunctionStatement_06() { var text = @" local(); static void local() { System.Console.WriteLine(""Hi!""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void LocalFunctionStatement_07() { var text1 = @" local1(1); void local1(int x) {} local2(); "; var text2 = @" void local1(byte y) {} void local2() { local1(2); } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // void local1(byte y) Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "void").WithLocation(2, 1), // (5,1): error CS0103: The name 'local2' does not exist in the current context // local2(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local2").WithArguments("local2").WithLocation(5, 1), // (5,6): warning CS8321: The local function 'local2' is declared but never used // void local2() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local2").WithArguments("local2").WithLocation(5, 6) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var symbol1 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single()); Assert.Equal("void local1(System.Int32 x)", symbol1.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "local1").Single()).Symbol); var tree2 = comp.SyntaxTrees[1]; var model2 = comp.GetSemanticModel(tree2); var symbol2 = model2.GetDeclaredSymbol(tree2.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().First()); Assert.Equal("void local1(System.Byte y)", symbol2.ToTestDisplayString()); Assert.Same(symbol2, model2.GetSymbolInfo(tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "local1").Single()).Symbol); } [Fact] public void LocalFunctionStatement_08() { var text = @" void local() { System.Console.WriteLine(""Hi!""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,6): warning CS8321: The local function 'local' is declared but never used // void local() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(2, 6) ); CompileAndVerify(comp, expectedOutput: ""); } [Fact] public void LocalFunctionStatement_09() { var text1 = @" local1(1); void local1(int x) {} local2(); void local1(byte y) {} void local2() { local1(2); } "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (7,6): error CS0128: A local variable or function named 'local1' is already defined in this scope // void local1(byte y) Diagnostic(ErrorCode.ERR_LocalDuplicate, "local1").WithArguments("local1").WithLocation(7, 6), // (7,6): warning CS8321: The local function 'local1' is declared but never used // void local1(byte y) Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local1").WithArguments("local1").WithLocation(7, 6) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var symbol1 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().First()); Assert.Equal("void local1(System.Int32 x)", symbol1.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "local1").First()).Symbol); var symbol2 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Skip(1).First()); Assert.Equal("void local1(System.Byte y)", symbol2.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "local1").Skip(1).Single()).Symbol); } [Fact] public void LocalFunctionStatement_10() { var text = @" int i = 1; local(); System.Console.WriteLine(i); void local() { i++; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "2"); } [Fact] public void LocalFunctionStatement_11() { var text1 = @" args(1); void args(int x) {} "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,6): error CS0136: A local or parameter named 'args' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void args(int x) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "args").WithArguments("args").WithLocation(3, 6) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var symbol1 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().First()); Assert.Equal("void args(System.Int32 x)", symbol1.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "args").Single()).Symbol); } [Fact] public void LocalFunctionStatement_12() { var text1 = @" local(1); void local<args>(args x) { System.Console.WriteLine(x); } "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "1"); } [Fact] public void LocalFunctionStatement_13() { var text1 = @" local(); void local() { var args = 2; System.Console.WriteLine(args); } "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "2"); } [Fact] public void LocalFunctionStatement_14() { var text1 = @" local(3); void local(int args) { System.Console.WriteLine(args); } "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "3"); } [Fact] public void LocalFunctionStatement_15() { var text1 = @" local(); void local() { args(4); void args(int x) { System.Console.WriteLine(x); } } "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "4"); } [Fact] public void LocalFunctionStatement_16() { var text1 = @" using System.Linq; _ = from local in new object[0] select local; local(); void local() {} "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,10): error CS1931: The range variable 'local' conflicts with a previous declaration of 'local' // _ = from local in new object[0] select local; Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "local").WithArguments("local").WithLocation(3, 10) ); } [Fact] public void LocalFunctionStatement_17() { var text = @" System.Console.WriteLine(); string await() => ""Hi!""; System.Console.WriteLine(await()); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,8): error CS4003: 'await' cannot be used as an identifier within an async method or lambda expression // string await() => "Hi!"; Diagnostic(ErrorCode.ERR_BadAwaitAsIdentifier, "await").WithLocation(3, 8), // (3,8): warning CS8321: The local function 'await' is declared but never used // string await() => "Hi!"; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "await").WithArguments("await").WithLocation(3, 8), // (4,32): error CS1525: Invalid expression term ')' // System.Console.WriteLine(await()); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(4, 32) ); } [Fact] public void LocalFunctionStatement_18() { var text = @" string async() => ""Hi!""; System.Console.WriteLine(async()); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void Lambda_01() { var text = @" int i = 1; System.Action l = () => i++; l(); System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "2"); } [Fact] public void PropertyDeclaration_01() { var text = @" _ = local; int local => 1; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,5): error CS0103: The name 'local' does not exist in the current context // _ = local; Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(2, 5), // (4,5): error CS0116: A namespace cannot directly contain members such as fields or methods // int local => 1; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "local").WithLocation(4, 5) ); } [Fact] public void PropertyDeclaration_02() { var text = @" _ = local; int local { get => 1; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,5): error CS0103: The name 'local' does not exist in the current context // _ = local; Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(2, 5), // (4,5): error CS0116: A namespace cannot directly contain members such as fields or methods // int local { get => 1; } Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "local").WithLocation(4, 5) ); } [Fact] public void PropertyDeclaration_03() { var text = @" _ = local; int local { get { return 1; } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,5): error CS0103: The name 'local' does not exist in the current context // _ = local; Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(2, 5), // (4,5): error CS0116: A namespace cannot directly contain members such as fields or methods // int local { get { return 1; } } Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "local").WithLocation(4, 5) ); } [Fact] public void EventDeclaration_01() { var text = @" local += null; event System.Action local; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS0103: The name 'local' does not exist in the current context // local += null; Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(2, 1), // (4,21): error CS0116: A namespace cannot directly contain members such as fields or methods // event System.Action local; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "local").WithLocation(4, 21) ); } [Fact] public void EventDeclaration_02() { var text = @" local -= null; event System.Action local { add {} remove {} } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS0103: The name 'local' does not exist in the current context // local -= null; Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(2, 1), // (4,21): error CS0116: A namespace cannot directly contain members such as fields or methods // event System.Action local Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "local").WithLocation(4, 21) ); } [Fact] public void LabeledStatement_01() { var text = @" goto label1; label1: System.Console.WriteLine(""Hi!""); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<LabeledStatementSyntax>().Single(); var reference = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "label1").Single(); var label = model.GetDeclaredSymbol(declarator); Assert.Same(label, model.GetSymbolInfo(reference).Symbol); Assert.Equal("label1", label.ToTestDisplayString()); Assert.Equal(SymbolKind.Label, label.Kind); Assert.Equal(SymbolKind.Method, label.ContainingSymbol.Kind); Assert.False(label.ContainingSymbol.IsImplicitlyDeclared); Assert.Equal(SymbolKind.NamedType, label.ContainingSymbol.ContainingSymbol.Kind); Assert.False(label.ContainingSymbol.ContainingSymbol.IsImplicitlyDeclared); Assert.True(((INamespaceSymbol)label.ContainingSymbol.ContainingSymbol.ContainingSymbol).IsGlobalNamespace); } [Fact] public void LabeledStatement_02() { var text = @" goto label1; label1: System.Console.WriteLine(""Hi!""); label1: System.Console.WriteLine(); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,1): error CS0140: The label 'label1' is a duplicate // label1: System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_DuplicateLabel, "label1").WithArguments("label1").WithLocation(4, 1) ); } [Fact] public void LabeledStatement_03() { var text1 = @" goto label1; label1: System.Console.Write(1); "; var text2 = @" label1: System.Console.Write(2); goto label1; "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // label1: System.Console.Write(2); Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "label1").WithLocation(2, 1) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var symbol1 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<LabeledStatementSyntax>().Single()); Assert.Equal("label1", symbol1.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "label1").Single()).Symbol); var tree2 = comp.SyntaxTrees[1]; var model2 = comp.GetSemanticModel(tree2); var symbol2 = model2.GetDeclaredSymbol(tree2.GetRoot().DescendantNodes().OfType<LabeledStatementSyntax>().Single()); Assert.Equal("label1", symbol2.ToTestDisplayString()); Assert.NotEqual(symbol1, symbol2); Assert.Same(symbol2, model2.GetSymbolInfo(tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "label1").Single()).Symbol); } [Fact] public void LabeledStatement_04() { var text = @" goto args; args: System.Console.WriteLine(""Hi!""); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<LabeledStatementSyntax>().Single(); var reference = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "args").Single(); var label = model.GetDeclaredSymbol(declarator); Assert.Same(label, model.GetSymbolInfo(reference).Symbol); Assert.Equal("args", label.ToTestDisplayString()); Assert.Equal(SymbolKind.Label, label.Kind); Assert.Equal(SymbolKind.Method, label.ContainingSymbol.Kind); Assert.False(label.ContainingSymbol.IsImplicitlyDeclared); Assert.Equal(SymbolKind.NamedType, label.ContainingSymbol.ContainingSymbol.Kind); Assert.False(label.ContainingSymbol.ContainingSymbol.IsImplicitlyDeclared); Assert.True(((INamespaceSymbol)label.ContainingSymbol.ContainingSymbol.ContainingSymbol).IsGlobalNamespace); } [Fact] public void ExplicitMain_01() { var text = @" static void Main() {} System.Console.Write(""Hi!""); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,13): warning CS7022: The entry point of the program is global code; ignoring 'Main()' entry point. // static void Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main()").WithLocation(2, 13), // (2,13): warning CS8321: The local function 'Main' is declared but never used // static void Main() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Main").WithArguments("Main").WithLocation(2, 13) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_02() { var text = @" System.Console.Write(""H""); Main(); System.Console.Write(""!""); static void Main() { System.Console.Write(""i""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,13): warning CS7022: The entry point of the program is global code; ignoring 'Main()' entry point. // static void Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main()").WithLocation(6, 13) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_03() { var text = @" using System; using System.Threading.Tasks; System.Console.Write(""Hi!""); class Program { static async Task Main() { Console.Write(""hello ""); await Task.Factory.StartNew(() => 5); Console.Write(""async main""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (9,23): warning CS7022: The entry point of the program is global code; ignoring 'Program.Main()' entry point. // static async Task Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program.Main()").WithLocation(9, 23) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_04() { var text = @" using System; using System.Threading.Tasks; await Task.Factory.StartNew(() => 5); System.Console.Write(""Hi!""); class Program { static async Task Main() { Console.Write(""hello ""); await Task.Factory.StartNew(() => 5); Console.Write(""async main""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (10,23): warning CS7022: The entry point of the program is global code; ignoring 'Program.Main()' entry point. // static async Task Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program.Main()").WithLocation(10, 23) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_05() { var text = @" using System; using System.Threading.Tasks; await Task.Factory.StartNew(() => 5); System.Console.Write(""Hi!""); class Program { static void Main() { Console.Write(""hello ""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (10,17): warning CS7022: The entry point of the program is global code; ignoring 'Program.Main()' entry point. // static void Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program.Main()").WithLocation(10, 17) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_06() { var text = @" System.Console.Write(""Hi!""); class Program { static void Main() { System.Console.Write(""hello ""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,17): warning CS7022: The entry point of the program is global code; ignoring 'Program.Main()' entry point. // static void Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program.Main()").WithLocation(6, 17) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_07() { var text = @" using System; using System.Threading.Tasks; System.Console.Write(""Hi!""); class Program { static void Main(string[] args) { Console.Write(""hello ""); } static async Task Main() { Console.Write(""hello ""); await Task.Factory.StartNew(() => 5); Console.Write(""async main""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (9,17): warning CS7022: The entry point of the program is global code; ignoring 'Program.Main(string[])' entry point. // static void Main(string[] args) Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program.Main(string[])").WithLocation(9, 17), // (14,23): warning CS7022: The entry point of the program is global code; ignoring 'Program.Main()' entry point. // static async Task Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program.Main()").WithLocation(14, 23) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_08() { var text = @" using System; using System.Threading.Tasks; await Task.Factory.StartNew(() => 5); System.Console.Write(""Hi!""); class Program { static void Main() { Console.Write(""hello ""); } static async Task Main(string[] args) { await Task.Factory.StartNew(() => 5); Console.Write(""async main""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (10,17): warning CS7022: The entry point of the program is global code; ignoring 'Program.Main()' entry point. // static void Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program.Main()").WithLocation(10, 17), // (15,23): warning CS7022: The entry point of the program is global code; ignoring 'Program.Main(string[])' entry point. // static async Task Main(string[] args) Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program.Main(string[])").WithLocation(15, 23) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_09() { var text1 = @" using System; using System.Threading.Tasks; string s = ""Hello world!""; foreach (var c in s) { await N1.Helpers.Wait(); Console.Write(c); } Console.WriteLine(); namespace N1 { class Helpers { static void Main() { } public static async Task Wait() { await Task.Delay(500); } } }"; var text4 = @" using System.Threading.Tasks; class Helpers { public static async Task Wait() { await Task.Delay(500); } } "; var comp = CreateCompilation(new[] { text1, text4 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // (19,21): warning CS7022: The entry point of the program is global code; ignoring 'Helpers.Main()' entry point. // static void Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("N1.Helpers.Main()").WithLocation(19, 21) ); } [Fact] public void ExplicitMain_10() { var text = @" using System.Threading.Tasks; System.Console.Write(""Hi!""); class Program { static void Main() { } static async Task Main(string[] args) { await Task.Factory.StartNew(() => 5); } } class Program2 { static void Main(string[] args) { } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe.WithMainTypeName("Program"), parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // error CS8804: Cannot specify /main if there is a compilation unit with top-level statements. Diagnostic(ErrorCode.ERR_SimpleProgramDisallowsMainType).WithLocation(1, 1), // (12,23): warning CS8892: Method 'Program.Main(string[])' will not be used as an entry point because a synchronous entry point 'Program.Main()' was found. // static async Task Main(string[] args) Diagnostic(ErrorCode.WRN_SyncAndAsyncEntryPoints, "Main").WithArguments("Program.Main(string[])", "Program.Main()").WithLocation(12, 23) ); } [Fact] public void ExplicitMain_11() { var text = @" using System.Threading.Tasks; System.Console.Write(""Hi!""); class Program { static void Main() { } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe.WithMainTypeName(""), parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // error CS7088: Invalid 'MainTypeName' value: ''. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("MainTypeName", "").WithLocation(1, 1), // error CS8804: Cannot specify /main if there is a compilation unit with top-level statements. Diagnostic(ErrorCode.ERR_SimpleProgramDisallowsMainType).WithLocation(1, 1) ); } [Fact] public void ExplicitMain_12() { var text = @" System.Console.Write(""H""); Main(); System.Console.Write(""!""); void Main() { System.Console.Write(""i""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_13() { var text = @" System.Console.Write(""H""); Main(""""); System.Console.Write(""!""); static void Main(string args) { System.Console.Write(""i""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_14() { var text = @" System.Console.Write(""H""); Main(); System.Console.Write(""!""); static long Main() { System.Console.Write(""i""); return 0; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_15() { var text = @" System.Console.Write(""H""); Main(); System.Console.Write(""!""); static int Main() { System.Console.Write(""i""); return 0; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,12): warning CS7022: The entry point of the program is global code; ignoring 'Main()' entry point. // static int Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main()").WithLocation(6, 12) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_16() { var text = @" System.Console.Write(""H""); Main(null); System.Console.Write(""!""); static void Main(string[] args) { System.Console.Write(""i""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,13): warning CS7022: The entry point of the program is global code; ignoring 'Main(string[])' entry point. // static void Main(string[] args) Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main(string[])").WithLocation(6, 13) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_17() { var text = @" System.Console.Write(""H""); Main(null); System.Console.Write(""!""); static int Main(string[] args) { System.Console.Write(""i""); return 0; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,12): warning CS7022: The entry point of the program is global code; ignoring 'Main(string[])' entry point. // static int Main(string[] args) Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main(string[])").WithLocation(6, 12) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_18() { var text = @" using System.Threading.Tasks; System.Console.Write(""H""); await Main(); System.Console.Write(""!""); async static Task Main() { System.Console.Write(""i""); await Task.Yield(); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (8,19): warning CS7022: The entry point of the program is global code; ignoring 'Main()' entry point. // async static Task Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main()").WithLocation(8, 19) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_19() { var text = @" using System.Threading.Tasks; System.Console.Write(""H""); await Main(); System.Console.Write(""!""); static async Task<int> Main() { System.Console.Write(""i""); await Task.Yield(); return 0; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (8,24): warning CS7022: The entry point of the program is global code; ignoring 'Main()' entry point. // static async Task<int> Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main()").WithLocation(8, 24) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_20() { var text = @" using System.Threading.Tasks; System.Console.Write(""H""); await Main(null); System.Console.Write(""!""); static async Task Main(string[] args) { System.Console.Write(""i""); await Task.Yield(); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (8,19): warning CS7022: The entry point of the program is global code; ignoring 'Main(string[])' entry point. // static async Task Main(string[] args) Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main(string[])").WithLocation(8, 19) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_21() { var text = @" using System.Threading.Tasks; System.Console.Write(""H""); await Main(null); System.Console.Write(""!""); static async Task<int> Main(string[] args) { System.Console.Write(""i""); await Task.Yield(); return 0; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (8,24): warning CS7022: The entry point of the program is global code; ignoring 'Main(string[])' entry point. // static async Task<int> Main(string[] args) Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main(string[])").WithLocation(8, 24) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_22() { var text = @" System.Console.Write(""H""); Main<int>(); System.Console.Write(""!""); static void Main<T>() { System.Console.Write(""i""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_23() { var text = @" System.Console.Write(""H""); local(); System.Console.Write(""!""); static void local() { Main(); static void Main() { System.Console.Write(""i""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void Yield_01() { var text = @"yield break;"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS1624: The body of '<top-level-statements-entry-point>' cannot be an iterator block because 'void' is not an iterator interface type // yield break; Diagnostic(ErrorCode.ERR_BadIteratorReturn, "yield break;").WithArguments("<top-level-statements-entry-point>", "void").WithLocation(1, 1) ); } [Fact] public void Yield_02() { var text = @"{yield return 0;}"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS1624: The body of '<top-level-statements-entry-point>' cannot be an iterator block because 'void' is not an iterator interface type // {yield return 0;} Diagnostic(ErrorCode.ERR_BadIteratorReturn, "{yield return 0;}").WithArguments("<top-level-statements-entry-point>", "void").WithLocation(1, 1) ); } [Fact] public void OutOfOrder_01() { var text = @" class C {} System.Console.WriteLine(1); System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(4, 1) ); } [Fact] public void OutOfOrder_02() { var text = @" System.Console.WriteLine(0); namespace C {} System.Console.WriteLine(1); System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(6, 1) ); } [Fact] public void OutOfOrder_03() { var text = @" class C {} System.Console.WriteLine(1); System.Console.WriteLine(2); class D {} System.Console.WriteLine(3); System.Console.WriteLine(4); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(4, 1) ); } [Fact] public void OutOfOrder_04() { var text = @" System.Console.WriteLine(0); namespace C {} System.Console.WriteLine(1); System.Console.WriteLine(2); namespace D {} System.Console.WriteLine(3); System.Console.WriteLine(4); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(6, 1) ); } [Fact] public void OutOfOrder_05() { var text = @" System.Console.WriteLine(0); struct S {} System.Console.WriteLine(1); System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(6, 1) ); } [Fact] public void OutOfOrder_06() { var text = @" System.Console.WriteLine(0); enum C { V } System.Console.WriteLine(1); System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(6, 1) ); } [Fact] public void OutOfOrder_07() { var text = @" System.Console.WriteLine(0); interface C {} System.Console.WriteLine(1); System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(6, 1) ); } [Fact] public void OutOfOrder_08() { var text = @" System.Console.WriteLine(0); delegate void D (); System.Console.WriteLine(1); System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(6, 1) ); } [Fact] public void OutOfOrder_09() { var text = @" System.Console.WriteLine(0); using System; Console.WriteLine(1); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,1): error CS1529: A using clause must precede all other elements defined in the namespace except extern alias declarations // using System; Diagnostic(ErrorCode.ERR_UsingAfterElements, "using System;").WithLocation(4, 1), // (6,1): error CS0103: The name 'Console' does not exist in the current context // Console.WriteLine(1); Diagnostic(ErrorCode.ERR_NameNotInContext, "Console").WithArguments("Console").WithLocation(6, 1) ); } [Fact] public void OutOfOrder_10() { var text = @" System.Console.WriteLine(0); [module: MyAttribute] class MyAttribute : System.Attribute {} "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,2): error CS1730: Assembly and module attributes must precede all other elements defined in a file except using clauses and extern alias declarations // [module: MyAttribute] Diagnostic(ErrorCode.ERR_GlobalAttributesNotFirst, "module").WithLocation(4, 2) ); } [Fact] public void OutOfOrder_11() { var text = @" System.Console.WriteLine(0); extern alias A; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,1): error CS0439: An extern alias declaration must precede all other elements defined in the namespace // extern alias A; Diagnostic(ErrorCode.ERR_ExternAfterElements, "extern").WithLocation(4, 1) ); } [Fact] public void OutOfOrder_12() { var text = @" extern alias A; using System; [module: MyAttribute] Console.WriteLine(1); class MyAttribute : System.Attribute {} "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): hidden CS8020: Unused extern alias. // extern alias A; Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias A;").WithLocation(2, 1), // (2,14): error CS0430: The extern alias 'A' was not specified in a /reference option // extern alias A; Diagnostic(ErrorCode.ERR_BadExternAlias, "A").WithArguments("A").WithLocation(2, 14) ); } [Fact] public void OutOfOrder_13() { var text = @" local(); class C {} void local() => System.Console.WriteLine(1); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,1): error CS8803: Top-level statements must precede namespace and type declarations. // void local() => System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "void local() => System.Console.WriteLine(1);").WithLocation(6, 1) ); } [Fact] public void Attributes_01() { var text1 = @" [MyAttribute(i)] const int i = 1; [MyAttribute(i + 1)] System.Console.Write(i); [MyAttribute(i + 2)] int j = i; System.Console.Write(j); [MyAttribute(i + 3)] new MyAttribute(i); [MyAttribute(i + 4)] local(); [MyAttribute(i + 5)] void local() {} class MyAttribute : System.Attribute { public MyAttribute(int x) {} } "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS7014: Attributes are not valid in this context. // [MyAttribute(i)] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[MyAttribute(i)]").WithLocation(2, 1), // (5,1): error CS7014: Attributes are not valid in this context. // [MyAttribute(i + 1)] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[MyAttribute(i + 1)]").WithLocation(5, 1), // (8,1): error CS7014: Attributes are not valid in this context. // [MyAttribute(i + 2)] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[MyAttribute(i + 2)]").WithLocation(8, 1), // (12,1): error CS7014: Attributes are not valid in this context. // [MyAttribute(i + 3)] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[MyAttribute(i + 3)]").WithLocation(12, 1), // (16,1): error CS0246: The type or namespace name 'local' could not be found (are you missing a using directive or an assembly reference?) // local(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "local").WithArguments("local").WithLocation(16, 1), // (16,6): error CS1001: Identifier expected // local(); Diagnostic(ErrorCode.ERR_IdentifierExpected, "(").WithLocation(16, 6), // (16,6): error CS8112: Local function '()' must declare a body because it is not marked 'static extern'. // local(); Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "").WithArguments("()").WithLocation(16, 6), // (19,6): warning CS8321: The local function 'local' is declared but never used // void local() {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(19, 6) ); var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.Int32 i", declSymbol.ToTestDisplayString()); var localRefs = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "i").ToArray(); Assert.Equal(9, localRefs.Length); foreach (var localRef in localRefs) { var refSymbol = model1.GetSymbolInfo(localRef).Symbol; Assert.Same(declSymbol, refSymbol); Assert.Contains(declSymbol.Name, model1.LookupNames(localRef.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localRef.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localRef.SpanStart, name: declSymbol.Name).Single()); } localDecl = tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ElementAt(1); declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.Int32 j", declSymbol.ToTestDisplayString()); } [Fact] public void Attributes_02() { var source = @" using System.Runtime.CompilerServices; return; #pragma warning disable 8321 // Unreferenced local function [MethodImpl(MethodImplOptions.ForwardRef)] static void forwardRef() { System.Console.WriteLine(0); } [MethodImpl(MethodImplOptions.NoInlining)] static void noInlining() { System.Console.WriteLine(1); } [MethodImpl(MethodImplOptions.NoOptimization)] static void noOptimization() { System.Console.WriteLine(2); } [MethodImpl(MethodImplOptions.Synchronized)] static void synchronized() { System.Console.WriteLine(3); } [MethodImpl(MethodImplOptions.InternalCall)] extern static void internalCallStatic(); "; var verifier = CompileAndVerify( source, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: DefaultParseOptions, assemblyValidator: validateAssembly, verify: Verification.Skipped); var comp = verifier.Compilation; var syntaxTree = comp.SyntaxTrees.Single(); var semanticModel = comp.GetSemanticModel(syntaxTree); var localFunctions = syntaxTree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().ToList(); checkImplAttributes(localFunctions[0], MethodImplAttributes.ForwardRef); checkImplAttributes(localFunctions[1], MethodImplAttributes.NoInlining); checkImplAttributes(localFunctions[2], MethodImplAttributes.NoOptimization); checkImplAttributes(localFunctions[3], MethodImplAttributes.Synchronized); checkImplAttributes(localFunctions[4], MethodImplAttributes.InternalCall); void checkImplAttributes(LocalFunctionStatementSyntax localFunctionStatement, MethodImplAttributes expectedFlags) { var localFunction = semanticModel.GetDeclaredSymbol(localFunctionStatement).GetSymbol<LocalFunctionSymbol>(); Assert.Equal(expectedFlags, localFunction.ImplementationAttributes); } void validateAssembly(PEAssembly assembly) { var peReader = assembly.GetMetadataReader(); foreach (var methodHandle in peReader.MethodDefinitions) { var methodDef = peReader.GetMethodDefinition(methodHandle); var actualFlags = methodDef.ImplAttributes; var methodName = peReader.GetString(methodDef.Name); var expectedFlags = methodName switch { "<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">g__forwardRef|0_0" => MethodImplAttributes.ForwardRef, "<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">g__noInlining|0_1" => MethodImplAttributes.NoInlining, "<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">g__noOptimization|0_2" => MethodImplAttributes.NoOptimization, "<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">g__synchronized|0_3" => MethodImplAttributes.Synchronized, "<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">g__internalCallStatic|0_4" => MethodImplAttributes.InternalCall, ".ctor" => MethodImplAttributes.IL, WellKnownMemberNames.TopLevelStatementsEntryPointMethodName => MethodImplAttributes.IL, _ => throw TestExceptionUtilities.UnexpectedValue(methodName) }; Assert.Equal(expectedFlags, actualFlags); } } } [Fact] public void Attributes_03() { var source = @" using System.Runtime.InteropServices; local1(); [DllImport( ""something.dll"", EntryPoint = ""a"", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true, PreserveSig = false, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] static extern void local1(); "; var verifier = CompileAndVerify( source, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: DefaultParseOptions, symbolValidator: validate, verify: Verification.Skipped); var comp = verifier.Compilation; var syntaxTree = comp.SyntaxTrees.Single(); var semanticModel = comp.GetSemanticModel(syntaxTree); var localFunction = semanticModel .GetDeclaredSymbol(syntaxTree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single()) .GetSymbol<LocalFunctionSymbol>(); Assert.Equal(new[] { "DllImportAttribute" }, GetAttributeNames(localFunction.GetAttributes())); validateLocalFunction(localFunction); void validate(ModuleSymbol module) { var cClass = module.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName); Assert.Equal(new[] { "CompilerGeneratedAttribute" }, GetAttributeNames(cClass.GetAttributes().As<CSharpAttributeData>())); Assert.Empty(cClass.GetMethod(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName).GetAttributes()); var localFn1 = cClass.GetMethod("<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">g__local1|0_0"); Assert.Empty(localFn1.GetAttributes()); validateLocalFunction(localFn1); } static void validateLocalFunction(MethodSymbol localFunction) { Assert.True(localFunction.IsExtern); var importData = localFunction.GetDllImportData(); Assert.NotNull(importData); Assert.Equal("something.dll", importData.ModuleName); Assert.Equal("a", importData.EntryPointName); Assert.Equal(CharSet.Ansi, importData.CharacterSet); Assert.True(importData.SetLastError); Assert.True(importData.ExactSpelling); Assert.Equal(MethodImplAttributes.IL, localFunction.ImplementationAttributes); Assert.Equal(CallingConvention.Cdecl, importData.CallingConvention); Assert.False(importData.BestFitMapping); Assert.True(importData.ThrowOnUnmappableCharacter); } } [Fact] public void ModelWithIgnoredAccessibility_01() { var source = @" new A().M(); class A { A M() { return new A(); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,9): error CS0122: 'A.M()' is inaccessible due to its protection level // new A().M(); Diagnostic(ErrorCode.ERR_BadAccess, "M").WithArguments("A.M()").WithLocation(2, 9) ); var a = ((Compilation)comp).SourceModule.GlobalNamespace.GetTypeMember("A"); var syntaxTree = comp.SyntaxTrees.Single(); var invocation = syntaxTree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var semanticModel = comp.GetSemanticModel(syntaxTree); Assert.Equal("A", semanticModel.GetTypeInfo(invocation).Type.Name); Assert.Null(semanticModel.GetSymbolInfo(invocation).Symbol); Assert.Equal("M", semanticModel.GetSymbolInfo(invocation).CandidateSymbols.Single().Name); Assert.Equal(CandidateReason.Inaccessible, semanticModel.GetSymbolInfo(invocation).CandidateReason); Assert.Empty(semanticModel.LookupSymbols(invocation.SpanStart, container: a, name: "M")); semanticModel = comp.GetSemanticModel(syntaxTree, ignoreAccessibility: true); Assert.Equal("A", semanticModel.GetTypeInfo(invocation).Type.Name); Assert.Equal("M", semanticModel.GetSymbolInfo(invocation).Symbol.Name); Assert.NotEmpty(semanticModel.LookupSymbols(invocation.SpanStart, container: a, name: "M")); } [Fact] public void ModelWithIgnoredAccessibility_02() { var source = @" var x = new A().M(); class A { A M() { x = null; return new A(); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,17): error CS0122: 'A.M()' is inaccessible due to its protection level // var x = new A().M(); Diagnostic(ErrorCode.ERR_BadAccess, "M").WithArguments("A.M()").WithLocation(2, 17), // (8,9): error CS8801: Cannot use local variable or local function 'x' declared in a top-level statement in this context. // x = null; Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "x").WithArguments("x").WithLocation(8, 9) ); var a = ((Compilation)comp).SourceModule.GlobalNamespace.GetTypeMember("A"); var syntaxTree = comp.SyntaxTrees.Single(); var localDecl = syntaxTree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var localRef = syntaxTree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Single(); var semanticModel = comp.GetSemanticModel(syntaxTree, ignoreAccessibility: true); var x = semanticModel.GetDeclaredSymbol(localDecl); Assert.Same(x, semanticModel.LookupSymbols(localDecl.SpanStart, name: "x").Single()); Assert.Same(x, semanticModel.GetSymbolInfo(localRef).Symbol); Assert.Same(x, semanticModel.LookupSymbols(localRef.SpanStart, name: "x").Single()); } [Fact] public void ModelWithIgnoredAccessibility_03() { var source = @" var x = new B().M(1); class A { public long M(long i) => i; } class B : A { protected int M(int i) { _ = x; return i; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,13): error CS8801: Cannot use local variable or local function 'x' declared in a top-level statement in this context. // _ = x; Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "x").WithArguments("x").WithLocation(13, 13) ); var a = ((Compilation)comp).SourceModule.GlobalNamespace.GetTypeMember("A"); var syntaxTree1 = comp.SyntaxTrees.Single(); var localDecl = syntaxTree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var localRef = syntaxTree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Single(); verifyModel(ignoreAccessibility: true, "System.Int32"); verifyModel(ignoreAccessibility: false, "System.Int64"); void verifyModel(bool ignoreAccessibility, string expectedType) { var semanticModel1 = comp.GetSemanticModel(syntaxTree1, ignoreAccessibility); var xDecl = semanticModel1.GetDeclaredSymbol(localDecl); Assert.Same(xDecl, semanticModel1.LookupSymbols(localDecl.SpanStart, name: "x").Single()); var xRef = semanticModel1.GetSymbolInfo(localRef).Symbol; Assert.Same(xRef, semanticModel1.LookupSymbols(localRef.SpanStart, name: "x").Single()); Assert.Equal(expectedType, ((ILocalSymbol)xRef).Type.ToTestDisplayString()); Assert.Equal(expectedType, ((ILocalSymbol)xDecl).Type.ToTestDisplayString()); Assert.Same(xDecl, xRef); } } [Fact] public void ModelWithIgnoredAccessibility_04() { var source1 = @" var x = new B().M(1); "; var source2 = @" class A { public long M(long i) => i; } class B : A { protected int M(int i) { _ = x; return i; } } "; var comp = CreateCompilation(new[] { source1, source2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (11,13): error CS8801: Cannot use local variable or local function 'x' declared in a top-level statement in this context. // _ = x; Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "x").WithArguments("x").WithLocation(11, 13) ); var a = ((Compilation)comp).SourceModule.GlobalNamespace.GetTypeMember("A"); var syntaxTree1 = comp.SyntaxTrees.First(); var localDecl = syntaxTree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var syntaxTree2 = comp.SyntaxTrees[1]; var localRef = syntaxTree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Single(); verifyModel(ignoreAccessibility: true, "System.Int32"); verifyModel(ignoreAccessibility: false, "System.Int64"); void verifyModel(bool ignoreAccessibility, string expectedType) { var semanticModel1 = comp.GetSemanticModel(syntaxTree1, ignoreAccessibility); var xDecl = semanticModel1.GetDeclaredSymbol(localDecl); Assert.Same(xDecl, semanticModel1.LookupSymbols(localDecl.SpanStart, name: "x").Single()); Assert.Equal(expectedType, ((ILocalSymbol)xDecl).Type.ToTestDisplayString()); var semanticModel2 = comp.GetSemanticModel(syntaxTree2, ignoreAccessibility); var xRef = semanticModel2.GetSymbolInfo(localRef).Symbol; Assert.Same(xRef, semanticModel2.LookupSymbols(localRef.SpanStart, name: "x").Single()); Assert.Equal(expectedType, ((ILocalSymbol)xRef).Type.ToTestDisplayString()); Assert.Same(xDecl, xRef); } } [Fact] public void AnalyzerActions_01() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_01_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(0, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(0, analyzer.FireCount6); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_01_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); } private class AnalyzerActions_01_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.GlobalStatement); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.CompilationUnit); } private void Handle1(SyntaxNodeAnalysisContext context) { var model = context.SemanticModel; var globalStatement = (GlobalStatementSyntax)context.Node; var syntaxTreeModel = ((SyntaxTreeSemanticModel)model); switch (globalStatement.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } Assert.Equal("<top-level-statements-entry-point>", context.ContainingSymbol.ToTestDisplayString()); Assert.Same(globalStatement.SyntaxTree, context.ContainingSymbol.DeclaringSyntaxReferences.Single().SyntaxTree); Assert.True(syntaxTreeModel.TestOnlyMemberModels.ContainsKey(globalStatement.Parent)); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[globalStatement.Parent]; Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(globalStatement.Statement).IsDefaultOrEmpty); Assert.Same(mm, syntaxTreeModel.GetMemberModel(globalStatement.Statement)); } private void Handle2(SyntaxNodeAnalysisContext context) { var model = context.SemanticModel; var unit = (CompilationUnitSyntax)context.Node; var syntaxTreeModel = ((SyntaxTreeSemanticModel)model); switch (unit.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref context.ContainingSymbol.Kind == SymbolKind.Namespace ? ref FireCount5 : ref FireCount3); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref context.ContainingSymbol.Kind == SymbolKind.Namespace ? ref FireCount6 : ref FireCount4); break; default: Assert.True(false); break; } switch (context.ContainingSymbol.ToTestDisplayString()) { case "<top-level-statements-entry-point>": Assert.Same(unit.SyntaxTree, context.ContainingSymbol.DeclaringSyntaxReferences.Single().SyntaxTree); Assert.True(syntaxTreeModel.TestOnlyMemberModels.ContainsKey(unit)); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[unit]; Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(unit).IsDefaultOrEmpty); Assert.Same(mm, syntaxTreeModel.GetMemberModel(unit)); break; case "<global namespace>": break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_02() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_02_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_02_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); } private class AnalyzerActions_02_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(Handle, SymbolKind.Method); } private void Handle(SymbolAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.Symbol.ToTestDisplayString()); switch (context.Symbol.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_03() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_03_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(0, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(0, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_03_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); } private class AnalyzerActions_03_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; public int FireCount8; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolStartAction(Handle1, SymbolKind.Method); context.RegisterSymbolStartAction(Handle2, SymbolKind.NamedType); } private void Handle1(SymbolStartAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.Symbol.ToTestDisplayString()); switch (context.Symbol.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); context.RegisterSymbolEndAction(Handle3); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); context.RegisterSymbolEndAction(Handle4); break; default: Assert.True(false); break; } } private void Handle2(SymbolStartAnalysisContext context) { Assert.Equal(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName, context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount3); context.RegisterSymbolEndAction(Handle5); foreach (var syntaxReference in context.Symbol.DeclaringSyntaxReferences) { switch (syntaxReference.GetSyntax().ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount4); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount5); break; default: Assert.True(false); break; } } } private void Handle3(SymbolAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount6); Assert.Equal("System.Console.WriteLine(1);", context.Symbol.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); } private void Handle4(SymbolAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount7); Assert.Equal("System.Console.WriteLine(2);", context.Symbol.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); } private void Handle5(SymbolAnalysisContext context) { Assert.Equal(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName, context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount8); } } [Fact] public void AnalyzerActions_04() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_04_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(0, analyzer.FireCount4); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_04_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); } private class AnalyzerActions_04_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationAction(Handle1, OperationKind.Invocation); context.RegisterOperationAction(Handle2, OperationKind.Block); } private void Handle1(OperationAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.ContainingSymbol.ToTestDisplayString()); Assert.Same(context.ContainingSymbol.DeclaringSyntaxReferences.Single().SyntaxTree, context.Operation.Syntax.SyntaxTree); Assert.Equal(SyntaxKind.InvocationExpression, context.Operation.Syntax.Kind()); switch (context.Operation.Syntax.ToString()) { case "System.Console.WriteLine(1)": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2)": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } } private void Handle2(OperationAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.ContainingSymbol.ToTestDisplayString()); Assert.Same(context.ContainingSymbol.DeclaringSyntaxReferences.Single().GetSyntax(), context.Operation.Syntax); Assert.Equal(SyntaxKind.CompilationUnit, context.Operation.Syntax.Kind()); switch (context.Operation.Syntax.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount3); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount4); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_05() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_05_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_05_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); } private class AnalyzerActions_05_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockAction(Handle); } private void Handle(OperationBlockAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.OwningSymbol.ToTestDisplayString()); Assert.Equal(SyntaxKind.CompilationUnit, context.OperationBlocks.Single().Syntax.Kind()); switch (context.OperationBlocks.Single().Syntax.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_06() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_06_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_06_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); } private class AnalyzerActions_06_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockStartAction(Handle); } private void Handle(OperationBlockStartAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.OwningSymbol.ToTestDisplayString()); Assert.Equal(SyntaxKind.CompilationUnit, context.OperationBlocks.Single().Syntax.Kind()); switch (context.OperationBlocks.Single().Syntax.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_07() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_07_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_07_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); } private class AnalyzerActions_07_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockAction(Handle); } private void Handle(CodeBlockAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.OwningSymbol.ToTestDisplayString()); Assert.Equal(SyntaxKind.CompilationUnit, context.CodeBlock.Kind()); switch (context.CodeBlock.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } var model = context.SemanticModel; var unit = (CompilationUnitSyntax)context.CodeBlock; var syntaxTreeModel = ((SyntaxTreeSemanticModel)model); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[unit]; Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(unit).IsDefaultOrEmpty); Assert.Same(mm, syntaxTreeModel.GetMemberModel(unit)); } } [Fact] public void AnalyzerActions_08() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_08_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_08_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); } private class AnalyzerActions_08_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockStartAction<SyntaxKind>(Handle); } private void Handle(CodeBlockStartAnalysisContext<SyntaxKind> context) { Assert.Equal("<top-level-statements-entry-point>", context.OwningSymbol.ToTestDisplayString()); Assert.Equal(SyntaxKind.CompilationUnit, context.CodeBlock.Kind()); switch (context.CodeBlock.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } var model = context.SemanticModel; var unit = (CompilationUnitSyntax)context.CodeBlock; var syntaxTreeModel = ((SyntaxTreeSemanticModel)model); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[unit]; Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(unit).IsDefaultOrEmpty); Assert.Same(mm, syntaxTreeModel.GetMemberModel(unit)); } } [Fact] public void AnalyzerActions_09() { var text1 = @" System.Console.WriteLine(""Hi!""); "; var text2 = @" class Test { void M() { M(); } } "; var analyzer = new AnalyzerActions_09_Analyzer(); var comp = CreateCompilation(text1 + text2, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); analyzer = new AnalyzerActions_09_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(2, analyzer.FireCount4); } private class AnalyzerActions_09_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.InvocationExpression); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.CompilationUnit); } private void Handle1(SyntaxNodeAnalysisContext context) { var model = context.SemanticModel; var node = (CSharpSyntaxNode)context.Node; var syntaxTreeModel = ((SyntaxTreeSemanticModel)model); switch (node.ToString()) { case @"System.Console.WriteLine(""Hi!"")": Interlocked.Increment(ref FireCount1); Assert.Equal("<top-level-statements-entry-point>", context.ContainingSymbol.ToTestDisplayString()); break; case "M()": Interlocked.Increment(ref FireCount2); Assert.Equal("void Test.M()", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } var decl = (CSharpSyntaxNode)context.ContainingSymbol.DeclaringSyntaxReferences.Single().GetSyntax(); Assert.True(syntaxTreeModel.TestOnlyMemberModels.ContainsKey(decl)); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[decl]; Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(node).IsDefaultOrEmpty); Assert.Same(mm, syntaxTreeModel.GetMemberModel(node)); } private void Handle2(SyntaxNodeAnalysisContext context) { var model = context.SemanticModel; var node = (CSharpSyntaxNode)context.Node; var syntaxTreeModel = ((SyntaxTreeSemanticModel)model); switch (context.ContainingSymbol.ToTestDisplayString()) { case @"<top-level-statements-entry-point>": Interlocked.Increment(ref FireCount3); Assert.True(syntaxTreeModel.TestOnlyMemberModels.ContainsKey(node)); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[node]; Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(node).IsDefaultOrEmpty); Assert.Same(mm, syntaxTreeModel.GetMemberModel(node)); break; case "<global namespace>": Interlocked.Increment(ref FireCount4); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_10() { var text1 = @" [assembly: MyAttribute(1)] "; var text2 = @" System.Console.WriteLine(""Hi!""); "; var text3 = @" [MyAttribute(2)] class Test { [MyAttribute(3)] void M() { } } class MyAttribute : System.Attribute { public MyAttribute(int x) {} } "; var analyzer = new AnalyzerActions_10_Analyzer(); var comp = CreateCompilation(text1 + text2 + text3, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); analyzer = new AnalyzerActions_10_Analyzer(); comp = CreateCompilation(new[] { text1, text2, text3 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(3, analyzer.FireCount5); } private class AnalyzerActions_10_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.Attribute); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.CompilationUnit); } private void Handle1(SyntaxNodeAnalysisContext context) { var node = (CSharpSyntaxNode)context.Node; switch (node.ToString()) { case @"MyAttribute(1)": Interlocked.Increment(ref FireCount1); Assert.Equal("<global namespace>", context.ContainingSymbol.ToTestDisplayString()); break; case @"MyAttribute(2)": Interlocked.Increment(ref FireCount2); Assert.Equal("Test", context.ContainingSymbol.ToTestDisplayString()); break; case @"MyAttribute(3)": Interlocked.Increment(ref FireCount3); Assert.Equal("void Test.M()", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } } private void Handle2(SyntaxNodeAnalysisContext context) { switch (context.ContainingSymbol.ToTestDisplayString()) { case @"<top-level-statements-entry-point>": Interlocked.Increment(ref FireCount4); break; case @"<global namespace>": Interlocked.Increment(ref FireCount5); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_11() { var text1 = @" System.Console.WriteLine(""Hi!""); "; var text2 = @" namespace N1 {} class C1 {} "; var analyzer = new AnalyzerActions_11_Analyzer(); var comp = CreateCompilation(text1 + text2, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); analyzer = new AnalyzerActions_11_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); } private class AnalyzerActions_11_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(Handle1, SymbolKind.Method); context.RegisterSymbolAction(Handle2, SymbolKind.Namespace); context.RegisterSymbolAction(Handle3, SymbolKind.NamedType); } private void Handle1(SymbolAnalysisContext context) { Interlocked.Increment(ref FireCount1); Assert.Equal("<top-level-statements-entry-point>", context.Symbol.ToTestDisplayString()); } private void Handle2(SymbolAnalysisContext context) { Interlocked.Increment(ref FireCount2); Assert.Equal("N1", context.Symbol.ToTestDisplayString()); } private void Handle3(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "C1": Interlocked.Increment(ref FireCount3); break; case WellKnownMemberNames.TopLevelStatementsEntryPointTypeName: Interlocked.Increment(ref FireCount4); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_12() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_12_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_12_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(2, analyzer.FireCount3); } private class AnalyzerActions_12_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockStartAction(Handle1); } private void Handle1(OperationBlockStartAnalysisContext context) { Interlocked.Increment(ref FireCount3); context.RegisterOperationBlockEndAction(Handle2); } private void Handle2(OperationBlockAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.OwningSymbol.ToTestDisplayString()); Assert.Equal(SyntaxKind.CompilationUnit, context.OperationBlocks.Single().Syntax.Kind()); switch (context.OperationBlocks.Single().Syntax.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_13() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_13_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_13_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(2, analyzer.FireCount3); } private class AnalyzerActions_13_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockStartAction(Handle1); } private void Handle1(OperationBlockStartAnalysisContext context) { Interlocked.Increment(ref FireCount3); context.RegisterOperationAction(Handle2, OperationKind.Block); } private void Handle2(OperationAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.ContainingSymbol.ToTestDisplayString()); Assert.Same(context.ContainingSymbol.DeclaringSyntaxReferences.Single().GetSyntax(), context.Operation.Syntax); Assert.Equal(SyntaxKind.CompilationUnit, context.Operation.Syntax.Kind()); switch (context.Operation.Syntax.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } } } [Fact] public void MissingTypes_01() { var text = @"return;"; var comp = CreateEmptyCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1), // error CS0518: Predefined type 'System.Object' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Object").WithLocation(1, 1), // error CS0518: Predefined type 'System.Void' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Void").WithLocation(1, 1), // error CS0518: Predefined type 'System.String' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.String").WithLocation(1, 1) ); } [Fact] public void MissingTypes_02() { var text = @"await Test();"; var comp = CreateCompilation(text, targetFramework: TargetFramework.Minimal, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // error CS0518: Predefined type 'System.Threading.Tasks.Task' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Threading.Tasks.Task").WithLocation(1, 1), // (1,1): warning CS0028: '<top-level-statements-entry-point>' has the wrong signature to be an entry point // await Test(); Diagnostic(ErrorCode.WRN_InvalidMainSig, "await Test();").WithArguments("<top-level-statements-entry-point>").WithLocation(1, 1), // error CS5001: Program does not contain a static 'Main' method suitable for an entry point Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1), // (1,7): error CS0103: The name 'Test' does not exist in the current context // await Test(); Diagnostic(ErrorCode.ERR_NameNotInContext, "Test").WithArguments("Test").WithLocation(1, 7) ); } [Fact] public void MissingTypes_03() { var text = @" System.Console.WriteLine(""Hi!""); return 10; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.MakeTypeMissing(SpecialType.System_Int32); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Int32[missing]", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); comp.VerifyEmitDiagnostics( // error CS0518: Predefined type 'System.Int32' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Int32").WithLocation(1, 1), // (3,8): error CS0518: Predefined type 'System.Int32' is not defined or imported // return 10; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "10").WithArguments("System.Int32").WithLocation(3, 8) ); } [Fact] public void MissingTypes_04() { var text = @" await System.Threading.Tasks.Task.Factory.StartNew(() => 5L); return 11; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.MakeTypeMissing(SpecialType.System_Int32); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task<System.Int32[missing]>", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); comp.VerifyEmitDiagnostics( // error CS0518: Predefined type 'System.Int32' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Int32").WithLocation(1, 1), // error CS5001: Program does not contain a static 'Main' method suitable for an entry point Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1), // (2,1): warning CS0028: '<top-level-statements-entry-point>' has the wrong signature to be an entry point // await System.Threading.Tasks.Task.Factory.StartNew(() => 5L); Diagnostic(ErrorCode.WRN_InvalidMainSig, @"await System.Threading.Tasks.Task.Factory.StartNew(() => 5L); return 11; ").WithArguments("<top-level-statements-entry-point>").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Int32' is not defined or imported // await System.Threading.Tasks.Task.Factory.StartNew(() => 5L); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await System.Threading.Tasks.Task.Factory.StartNew(() => 5L);").WithArguments("System.Int32").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Int32' is not defined or imported // await System.Threading.Tasks.Task.Factory.StartNew(() => 5L); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await System.Threading.Tasks.Task.Factory.StartNew(() => 5L);").WithArguments("System.Int32").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Int32' is not defined or imported // await System.Threading.Tasks.Task.Factory.StartNew(() => 5L); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await System.Threading.Tasks.Task.Factory.StartNew(() => 5L);").WithArguments("System.Int32").WithLocation(2, 1), // (3,8): error CS0518: Predefined type 'System.Int32' is not defined or imported // return 11; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "11").WithArguments("System.Int32").WithLocation(3, 8) ); } [Fact] public void MissingTypes_05() { var text = @" await System.Threading.Tasks.Task.Factory.StartNew(() => ""5""); return 11; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.MakeTypeMissing(WellKnownType.System_Threading_Tasks_Task_T); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task<System.Int32>[missing]", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); comp.VerifyEmitDiagnostics( // error CS0518: Predefined type 'System.Threading.Tasks.Task`1' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Threading.Tasks.Task`1").WithLocation(1, 1), // error CS5001: Program does not contain a static 'Main' method suitable for an entry point Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1), // (2,1): warning CS0028: '<top-level-statements-entry-point>' has the wrong signature to be an entry point // await System.Threading.Tasks.Task.Factory.StartNew(() => "5"); Diagnostic(ErrorCode.WRN_InvalidMainSig, @"await System.Threading.Tasks.Task.Factory.StartNew(() => ""5""); return 11; ").WithArguments("<top-level-statements-entry-point>").WithLocation(2, 1) ); } [Fact] public void MissingTypes_06() { var text = @" await System.Threading.Tasks.Task.Factory.StartNew(() => ""5""); return 11; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.MakeTypeMissing(SpecialType.System_Int32); comp.MakeTypeMissing(WellKnownType.System_Threading_Tasks_Task_T); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task<System.Int32[missing]>[missing]", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); comp.VerifyEmitDiagnostics( // error CS0518: Predefined type 'System.Threading.Tasks.Task`1' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Threading.Tasks.Task`1").WithLocation(1, 1), // error CS0518: Predefined type 'System.Int32' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Int32").WithLocation(1, 1), // error CS5001: Program does not contain a static 'Main' method suitable for an entry point Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1), // (2,1): warning CS0028: '<top-level-statements-entry-point>' has the wrong signature to be an entry point // await System.Threading.Tasks.Task.Factory.StartNew(() => "5"); Diagnostic(ErrorCode.WRN_InvalidMainSig, @"await System.Threading.Tasks.Task.Factory.StartNew(() => ""5""); return 11; ").WithArguments("<top-level-statements-entry-point>").WithLocation(2, 1), // (3,8): error CS0518: Predefined type 'System.Int32' is not defined or imported // return 11; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "11").WithArguments("System.Int32").WithLocation(3, 8) ); } [Fact] public void MissingTypes_07() { var text = @" System.Console.WriteLine(); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.MakeTypeMissing(SpecialType.System_String); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.String[missing][] args", entryPoint.Parameters.Single().ToTestDisplayString()); comp.VerifyEmitDiagnostics( // error CS0518: Predefined type 'System.String' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.String").WithLocation(1, 1) ); } [Fact] public void Return_01() { var text = @" System.Console.WriteLine(args[0]); return; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); Assert.True(entryPoint.ReturnsVoid); AssertEntryPointParameter(entryPoint); CompileAndVerify(comp, expectedOutput: "Return_01", args: new[] { "Return_01" }); if (ExecutionConditionUtil.IsWindows) { _ = ConditionalSkipReason.NativePdbRequiresDesktop; comp.VerifyPdb(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + "." + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName, @$"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" methodName=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }"" parameterNames=""args"" /> <methods> <method containingType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" name=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""2"" startColumn=""1"" endLine=""2"" endColumn=""35"" document=""1"" /> <entry offset=""0x9"" startLine=""3"" startColumn=""1"" endLine=""3"" endColumn=""8"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>", options: PdbValidationOptions.SkipConversionValidation); } } private static string EscapeForXML(string toEscape) { return toEscape.Replace("<", "&lt;").Replace(">", "&gt;"); } [Fact] public void Return_02() { var text = @" System.Console.WriteLine(args[0]); return 10; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Int32", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); AssertEntryPointParameter(entryPoint); CompileAndVerify(comp, expectedOutput: "Return_02", args: new[] { "Return_02" }, expectedReturnCode: 10); if (ExecutionConditionUtil.IsWindows) { _ = ConditionalSkipReason.NativePdbRequiresDesktop; comp.VerifyPdb(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + "." + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName, @$"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" methodName=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }"" parameterNames=""args"" /> <methods> <method containingType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" name=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""2"" startColumn=""1"" endLine=""2"" endColumn=""35"" document=""1"" /> <entry offset=""0x9"" startLine=""3"" startColumn=""1"" endLine=""3"" endColumn=""11"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>", options: PdbValidationOptions.SkipConversionValidation); } } [Fact] public void Return_03() { var text = @" using System; using System.Threading.Tasks; Console.Write(""hello ""); await Task.Factory.StartNew(() => 5); Console.Write(args[0]); return; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); AssertEntryPointParameter(entryPoint); CompileAndVerify(comp, expectedOutput: "hello Return_03", args: new[] { "Return_03" }); if (ExecutionConditionUtil.IsWindows) { _ = ConditionalSkipReason.NativePdbRequiresDesktop; comp.VerifyPdb(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + "+<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">d__0.MoveNext", @$"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" methodName=""&lt;Main&gt;"" parameterNames=""args"" /> <methods> <method containingType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }+&lt;{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }+&lt;&gt;c"" methodName=""&lt;{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }&gt;b__0_0"" /> <encLocalSlotMap> <slot kind=""27"" offset=""2"" /> <slot kind=""33"" offset=""76"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0xe"" startLine=""5"" startColumn=""1"" endLine=""5"" endColumn=""25"" document=""1"" /> <entry offset=""0x19"" startLine=""6"" startColumn=""1"" endLine=""6"" endColumn=""38"" document=""1"" /> <entry offset=""0x48"" hidden=""true"" document=""1"" /> <entry offset=""0x99"" startLine=""7"" startColumn=""1"" endLine=""7"" endColumn=""24"" document=""1"" /> <entry offset=""0xa7"" startLine=""8"" startColumn=""1"" endLine=""8"" endColumn=""8"" document=""1"" /> <entry offset=""0xa9"" hidden=""true"" document=""1"" /> <entry offset=""0xc1"" hidden=""true"" document=""1"" /> </sequencePoints> <asyncInfo> <catchHandler offset=""0xa9"" /> <kickoffMethod declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" methodName=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }"" parameterNames=""args"" /> <await yield=""0x5a"" resume=""0x75"" declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }+&lt;{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }&gt;d__0"" methodName=""MoveNext"" /> </asyncInfo> </method> </methods> </symbols>", options: PdbValidationOptions.SkipConversionValidation); } } [Fact] public void Return_04() { var text = @" using System; using System.Threading.Tasks; Console.Write(""hello ""); await Task.Factory.StartNew(() => 5); Console.Write(args[0]); return 11; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task<System.Int32>", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); AssertEntryPointParameter(entryPoint); CompileAndVerify(comp, expectedOutput: "hello Return_04", args: new[] { "Return_04" }, expectedReturnCode: 11); if (ExecutionConditionUtil.IsWindows) { _ = ConditionalSkipReason.NativePdbRequiresDesktop; comp.VerifyPdb(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + "+<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">d__0.MoveNext", @$"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" methodName=""&lt;Main&gt;"" parameterNames=""args"" /> <methods> <method containingType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }+&lt;{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }+&lt;&gt;c"" methodName=""&lt;{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }&gt;b__0_0"" /> <encLocalSlotMap> <slot kind=""27"" offset=""2"" /> <slot kind=""20"" offset=""2"" /> <slot kind=""33"" offset=""76"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0xe"" startLine=""5"" startColumn=""1"" endLine=""5"" endColumn=""25"" document=""1"" /> <entry offset=""0x19"" startLine=""6"" startColumn=""1"" endLine=""6"" endColumn=""38"" document=""1"" /> <entry offset=""0x48"" hidden=""true"" document=""1"" /> <entry offset=""0x99"" startLine=""7"" startColumn=""1"" endLine=""7"" endColumn=""24"" document=""1"" /> <entry offset=""0xa7"" startLine=""8"" startColumn=""1"" endLine=""8"" endColumn=""11"" document=""1"" /> <entry offset=""0xac"" hidden=""true"" document=""1"" /> <entry offset=""0xc6"" hidden=""true"" document=""1"" /> </sequencePoints> <asyncInfo> <catchHandler offset=""0xac"" /> <kickoffMethod declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" methodName=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }"" parameterNames=""args"" /> <await yield=""0x5a"" resume=""0x75"" declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }+&lt;{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }&gt;d__0"" methodName=""MoveNext"" /> </asyncInfo> </method> </methods> </symbols>", options: PdbValidationOptions.SkipConversionValidation); } } [Fact] public void Return_05() { var text = @" System.Console.WriteLine(""Hi!""); return ""error""; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Int32", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); comp.VerifyDiagnostics( // (3,8): error CS0029: Cannot implicitly convert type 'string' to 'int' // return "error"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""error""").WithArguments("string", "int").WithLocation(3, 8) ); } [Fact] public void Return_06() { var text = @" System.Func<int, int> d = n => { System.Console.WriteLine(""Hi!""); return n; }; d(0); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); Assert.True(entryPoint.ReturnsVoid); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void Return_07() { var text = @" System.Func<int, int> d = delegate(int n) { System.Console.WriteLine(""Hi!""); return n; }; d(0); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); Assert.True(entryPoint.ReturnsVoid); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void Return_08() { var text = @" System.Func<int, int> d = (n) => { System.Console.WriteLine(""Hi!""); return n; }; d(0); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); Assert.True(entryPoint.ReturnsVoid); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void Return_09() { var text = @" int local(int n) { System.Console.WriteLine(""Hi!""); return n; } local(0); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); Assert.True(entryPoint.ReturnsVoid); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void Return_10() { var text = @" bool b = true; if (b) return 0; else return; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Int32", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); comp.VerifyDiagnostics( // (6,5): error CS0126: An object of a type convertible to 'int' is required // return; Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("int").WithLocation(6, 5) ); } [Fact] public void Return_11() { var text = @" bool b = true; if (b) return; else return 0; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Int32", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); comp.VerifyDiagnostics( // (4,5): error CS0126: An object of a type convertible to 'int' is required // return; Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("int").WithLocation(4, 5) ); } [Fact] public void Return_12() { var text = @" System.Console.WriteLine(1); return; System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); CompileAndVerify(comp, expectedOutput: "1").VerifyDiagnostics( // (4,1): warning CS0162: Unreachable code detected // System.Console.WriteLine(2); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(4, 1) ); } [Fact] public void Return_13() { var text = @" System.Console.WriteLine(1); return 13; System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Int32", entryPoint.ReturnType.ToTestDisplayString()); CompileAndVerify(comp, expectedOutput: "1", expectedReturnCode: 13).VerifyDiagnostics( // (4,1): warning CS0162: Unreachable code detected // System.Console.WriteLine(2); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(4, 1) ); } [Fact] public void Return_14() { var text = @" System.Console.WriteLine(""Hi!""); return default; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Int32", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); CompileAndVerify(comp, expectedOutput: "Hi!", expectedReturnCode: 0); } [Fact] public void Return_15() { var text = @" using System; using System.Threading.Tasks; Console.Write(""hello ""); await Task.Factory.StartNew(() => 5); Console.Write(""async main""); return default; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task<System.Int32>", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); CompileAndVerify(comp, expectedOutput: "hello async main", expectedReturnCode: 0); } [Fact] public void Dll_01() { var text = @"System.Console.WriteLine(""Hi!"");"; var comp = CreateCompilation(text, options: TestOptions.DebugDll, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // (1,1): error CS8805: Program using top-level statements must be an executable. // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, @"System.Console.WriteLine(""Hi!"");").WithLocation(1, 1) ); } [Fact] public void NetModule_01() { var text = @"System.Console.WriteLine(""Hi!"");"; var comp = CreateCompilation(text, options: TestOptions.ReleaseModule, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // (1,1): error CS8805: Program using top-level statements must be an executable. // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, @"System.Console.WriteLine(""Hi!"");").WithLocation(1, 1) ); } [Fact] public void ExpressionStatement_01() { // Await expression is covered in other tests var text = @" new Test(0); // ObjectCreationExpression: Test x; x = new Test(1); // SimpleAssignmentExpression: x += 1; // AddAssignmentExpression: x -= 2; // SubtractAssignmentExpression: x *= 3; // MultiplyAssignmentExpression: x /= 4; // DivideAssignmentExpression: x %= 5; // ModuloAssignmentExpression: x &= 6; // AndAssignmentExpression: x |= 7; // OrAssignmentExpression: x ^= 8; // ExclusiveOrAssignmentExpression: x <<= 9; // LeftShiftAssignmentExpression: x >>= 10; // RightShiftAssignmentExpression: x++; // PostIncrementExpression: x--; // PostDecrementExpression: ++x; // PreIncrementExpression: --x; // PreDecrementExpression: System.Console.WriteLine(x.Count); // InvocationExpression: x?.WhenNotNull(); // ConditionalAccessExpression: x = null; x ??= new Test(-1); // CoalesceAssignmentExpression: System.Console.WriteLine(x.Count); // InvocationExpression: class Test { public readonly int Count; public Test(int count) { Count = count; if (count == 0) { System.Console.WriteLine(""Test..ctor""); } } public static Test operator +(Test x, int y) { return new Test(x.Count + 1); } public static Test operator -(Test x, int y) { return new Test(x.Count + 1); } public static Test operator *(Test x, int y) { return new Test(x.Count + 1); } public static Test operator /(Test x, int y) { return new Test(x.Count + 1); } public static Test operator %(Test x, int y) { return new Test(x.Count + 1); } public static Test operator &(Test x, int y) { return new Test(x.Count + 1); } public static Test operator |(Test x, int y) { return new Test(x.Count + 1); } public static Test operator ^(Test x, int y) { return new Test(x.Count + 1); } public static Test operator <<(Test x, int y) { return new Test(x.Count + 1); } public static Test operator >>(Test x, int y) { return new Test(x.Count + 1); } public static Test operator ++(Test x) { return new Test(x.Count + 1); } public static Test operator --(Test x) { return new Test(x.Count + 1); } public void WhenNotNull() { System.Console.WriteLine(""WhenNotNull""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: @"Test..ctor 15 WhenNotNull -1 "); } [Fact] public void Block_01() { var text = @" { System.Console.WriteLine(""Hi!""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void EmptyStatement_01() { var text = @" ; System.Console.WriteLine(""Hi!""); ; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void BreakStatement_01() { var text = @"break;"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS0139: No enclosing loop out of which to break or continue // break; Diagnostic(ErrorCode.ERR_NoBreakOrCont, "break;").WithLocation(1, 1) ); } [Fact] public void ContinueStatement_01() { var text = @"continue;"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS0139: No enclosing loop out of which to break or continue // continue; Diagnostic(ErrorCode.ERR_NoBreakOrCont, "continue;").WithLocation(1, 1) ); } [Fact] public void ThrowStatement_01() { var text = @"throw;"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause // throw; Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw").WithLocation(1, 1) ); } [Fact] public void ThrowStatement_02() { var text = @"throw null;"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp).VerifyIL("<top-level-statements-entry-point>", sequencePoints: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + "." + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName, source: text, expectedIL: @" { // Code size 2 (0x2) .maxstack 1 // sequence point: throw null; IL_0000: ldnull IL_0001: throw } "); } [Fact] public void DoStatement_01() { var text = @" int i = 1; do { i++; } while (i < 4); System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "4"); } [Fact] public void WhileStatement_01() { var text = @" int i = 1; while (i < 4) { i++; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "4"); } [Fact] public void ForStatement_01() { var text = @" int i = 1; for (;i < 4;) { i++; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "4"); } [Fact] public void CheckedStatement_01() { var text = @" int i = 1; i++; checked { i++; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "3").VerifyIL("<top-level-statements-entry-point>", sequencePoints: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + "." + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName, source: text, expectedIL: @" { // Code size 20 (0x14) .maxstack 2 .locals init (int V_0) //i // sequence point: int i = 1; IL_0000: ldc.i4.1 IL_0001: stloc.0 // sequence point: i++; IL_0002: ldloc.0 IL_0003: ldc.i4.1 IL_0004: add IL_0005: stloc.0 // sequence point: { IL_0006: nop // sequence point: i++; IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: add.ovf IL_000a: stloc.0 // sequence point: } IL_000b: nop // sequence point: System.Console.WriteLine(i); IL_000c: ldloc.0 IL_000d: call ""void System.Console.WriteLine(int)"" IL_0012: nop IL_0013: ret } "); } [Fact] public void UncheckedStatement_01() { var text = @" int i = 1; i++; unchecked { i++; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe.WithOverflowChecks(true), parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "3").VerifyIL("<top-level-statements-entry-point>", sequencePoints: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + "." + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName, source: text, expectedIL: @" { // Code size 20 (0x14) .maxstack 2 .locals init (int V_0) //i // sequence point: int i = 1; IL_0000: ldc.i4.1 IL_0001: stloc.0 // sequence point: i++; IL_0002: ldloc.0 IL_0003: ldc.i4.1 IL_0004: add.ovf IL_0005: stloc.0 // sequence point: { IL_0006: nop // sequence point: i++; IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: add IL_000a: stloc.0 // sequence point: } IL_000b: nop // sequence point: System.Console.WriteLine(i); IL_000c: ldloc.0 IL_000d: call ""void System.Console.WriteLine(int)"" IL_0012: nop IL_0013: ret } "); } [Fact] public void UnsafeStatement_01() { var text = @" unsafe { int* p = (int*)0; p++; System.Console.WriteLine((int)p); } "; var comp = CreateCompilation(text, options: TestOptions.UnsafeDebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "4", verify: Verification.Skipped); } [Fact] public void FixedStatement_01() { var text = @" fixed(int *p = &new C().i) {} class C { public int i = 2; } "; var comp = CreateCompilation(text, options: TestOptions.UnsafeDebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // (2,1): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // fixed(int *p = &new C().i) {} Diagnostic(ErrorCode.ERR_UnsafeNeeded, "fixed(int *p = &new C().i) {}").WithLocation(2, 1), // (2,7): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // fixed(int *p = &new C().i) {} Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int *").WithLocation(2, 7), // (2,16): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // fixed(int *p = &new C().i) {} Diagnostic(ErrorCode.ERR_UnsafeNeeded, "&new C().i").WithLocation(2, 16) ); } [Fact] public void LockStatement_01() { var text = @" int i = 1; lock (new object()) { i++; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "2"); } [Fact] public void IfStatement_01() { var text = @" int i = 1; if (i == 1) { i++; } else { i--; } if (i != 2) { i--; } else { i++; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "3"); } [Fact] public void SwitchStatement_01() { var text = @" int i = 1; switch (i) { case 1: i++; break; default: i--; break; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "2"); } [Fact] public void TryStatement_01() { var text = @" try { System.Console.Write(1); throw null; } catch { System.Console.Write(2); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "12"); } [Fact] public void Args_01() { var text = @" #nullable enable System.Console.WriteLine(args.Length == 0 ? 0 : -args[0].Length); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "0").VerifyDiagnostics(); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); AssertEntryPointParameter(entryPoint); } [Fact] public void Args_02() { var text1 = @" using System.Linq; _ = from args in new object[0] select args; "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,10): error CS1931: The range variable 'args' conflicts with a previous declaration of 'args' // _ = from args in new object[0] select args; Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "args").WithArguments("args").WithLocation(3, 10) ); } [Fact] public void Args_03() { var text = @" local(); void local() { System.Console.WriteLine(args[0]); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Args_03", args: new[] { "Args_03" }).VerifyDiagnostics(); } [Fact] public void Args_04() { var text = @" System.Action lambda = () => System.Console.WriteLine(args[0]); lambda(); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Args_04", args: new[] { "Args_04" }).VerifyDiagnostics(); } [Fact] public void Span_01() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; Span<int> span = default; _ = new { Span = span }; ", options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (5,11): error CS0828: Cannot assign 'Span<int>' to anonymous type property // _ = new { Span = span }; Diagnostic(ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, "Span = span").WithArguments("System.Span<int>").WithLocation(5, 11) ); } [Fact] public void Span_02() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; Span<int> outer; for (Span<int> inner = stackalloc int[10];; inner = outer) { outer = inner; } ", options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (7,13): error CS8352: Cannot use local 'inner' in this context because it may expose referenced variables outside of their declaration scope // outer = inner; Diagnostic(ErrorCode.ERR_EscapeLocal, "inner").WithArguments("inner").WithLocation(7, 13) ); } [Fact] [WorkItem(1179569, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1179569")] public void Issue1179569() { var text1 = @"Task v0123456789012345678901234567() { Console.Write(""start v0123456789012345678901234567""); await Task.Delay(2 * 1000); Console.Write(""end v0123456789012345678901234567""); } Task On01234567890123456() { return v0123456789012345678901234567(); } string return Task.WhenAll( Task.WhenAll(this.c01234567890123456789012345678.Select(v01234567 => On01234567890123456(v01234567))), Task.WhenAll(this.c01234567890123456789.Select(v01234567 => v01234567.U0123456789012345678901234()))); "; var oldTree = Parse(text: text1, options: TestOptions.RegularDefault); var text2 = @"Task v0123456789012345678901234567() { Console.Write(""start v0123456789012345678901234567""); await Task.Delay(2 * 1000); Console.Write(""end v0123456789012345678901234567""); } Task On01234567890123456() { return v0123456789012345678901234567(); } string[ return Task.WhenAll( Task.WhenAll(this.c01234567890123456789012345678.Select(v01234567 => On01234567890123456(v01234567))), Task.WhenAll(this.c01234567890123456789.Select(v01234567 => v01234567.U0123456789012345678901234()))); "; var newText = Microsoft.CodeAnalysis.Text.StringText.From(text2, System.Text.Encoding.UTF8); using var lexer = new Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.Lexer(newText, TestOptions.RegularDefault); using var parser = new Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LanguageParser(lexer, (CSharpSyntaxNode)oldTree.GetRoot(), new[] { new Microsoft.CodeAnalysis.Text.TextChangeRange(new Microsoft.CodeAnalysis.Text.TextSpan(282, 0), 1) }); var compilationUnit = (CompilationUnitSyntax)parser.ParseCompilationUnit().CreateRed(); var tree = CSharpSyntaxTree.Create(compilationUnit, TestOptions.RegularDefault, encoding: System.Text.Encoding.UTF8); Assert.Equal(text2, tree.GetText().ToString()); tree.VerifySource(); var fullParseTree = Parse(text: text2, options: TestOptions.RegularDefault); var nodes1 = tree.GetRoot().DescendantNodesAndTokensAndSelf(descendIntoTrivia: true).ToArray(); var nodes2 = fullParseTree.GetRoot().DescendantNodesAndTokensAndSelf(descendIntoTrivia: true).ToArray(); Assert.Equal(nodes1.Length, nodes2.Length); for (int i = 0; i < nodes1.Length; i++) { var node1 = nodes1[i]; var node2 = nodes2[i]; Assert.Equal(node1.RawKind, node2.RawKind); Assert.Equal(node1.Span, node2.Span); Assert.Equal(node1.FullSpan, node2.FullSpan); Assert.Equal(node1.ToString(), node2.ToString()); Assert.Equal(node1.ToFullString(), node2.ToFullString()); } } [Fact] public void TopLevelLocalReferencedInClass_IOperation() { var comp = CreateCompilation(@" int i = 1; class C { void M() /*<bind>*/{ _ = i; }/*</bind>*/ } ", options: TestOptions.ReleaseExe); var diagnostics = new[] { // (2,5): warning CS0219: The variable 'i' is assigned but its value is never used // int i = 1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(2, 5), // (7,13): error CS8801: Cannot use local variable or local function 'i' declared in a top-level statement in this context. // _ = i; Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "i").WithArguments("i").WithLocation(7, 13) }; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, @" IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '_ = i;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: var, IsInvalid) (Syntax: '_ = i') Left: IDiscardOperation (Symbol: var _) (OperationKind.Discard, Type: var) (Syntax: '_') Right: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'i') ", diagnostics); VerifyFlowGraphForTest<BlockSyntax>(comp, @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '_ = i;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: var, IsInvalid) (Syntax: '_ = i') Left: IDiscardOperation (Symbol: var _) (OperationKind.Discard, Type: var) (Syntax: '_') Right: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'i') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "); } [Fact] public void TopLevelLocalFunctionReferencedInClass_IOperation() { var comp = CreateCompilation(@" _ = """"; static void M1() {} void M2() {} class C { void M() /*<bind>*/{ M1(); M2(); }/*</bind>*/ } ", options: TestOptions.ReleaseExe); var diagnostics = new[] { // (3,13): warning CS8321: The local function 'M1' is declared but never used // static void M1() {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "M1").WithArguments("M1").WithLocation(3, 13), // (4,6): warning CS8321: The local function 'M2' is declared but never used // void M2() {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "M2").WithArguments("M2").WithLocation(4, 6), // (9,9): error CS8801: Cannot use local variable or local function 'M1' declared in a top-level statement in this context. // M1(); Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "M1").WithArguments("M1").WithLocation(9, 9), // (10,9): error CS8801: Cannot use local variable or local function 'M2' declared in a top-level statement in this context. // M2(); Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "M2").WithArguments("M2").WithLocation(10, 9) }; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, @" IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M1();') Expression: IInvocationOperation (void M1()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M1()') Instance Receiver: null Arguments(0) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M2();') Expression: IInvocationOperation (void M2()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M2()') Instance Receiver: null Arguments(0) ", diagnostics); VerifyFlowGraphForTest<BlockSyntax>(comp, @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M1();') Expression: IInvocationOperation (void M1()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M1()') Instance Receiver: null Arguments(0) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M2();') Expression: IInvocationOperation (void M2()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M2()') Instance Receiver: null Arguments(0) Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "); } [Fact] public void EmptyStatements_01() { var text = @";"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS8937: At least one top-level statement must be non-empty. // ; Diagnostic(ErrorCode.ERR_SimpleProgramIsEmpty, ";").WithLocation(1, 1) ); } [Fact] public void EmptyStatements_02() { var text = @";; ;; ;"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS8937: At least one top-level statement must be non-empty. // ;; Diagnostic(ErrorCode.ERR_SimpleProgramIsEmpty, ";").WithLocation(1, 1) ); } [Fact] public void EmptyStatements_03() { var text = @" System.Console.WriteLine(""Hi!""); ;; ; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void EmptyStatements_04() { var text = @" ;; ; System.Console.WriteLine(""Hi!"");"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void EmptyStatements_05() { var text = @" ; System.Console.WriteLine(""Hi!""); ; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void EmptyStatements_06() { var text = @" using System; ; class Program { static void Main(String[] args) {} } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,1): error CS8937: At least one top-level statement must be non-empty. // ; Diagnostic(ErrorCode.ERR_SimpleProgramIsEmpty, ";").WithLocation(3, 1), // (7,17): warning CS7022: The entry point of the program is global code; ignoring 'Program.Main(string[])' entry point. // static void Main(String[] args) {} Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program.Main(string[])").WithLocation(7, 17) ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.TopLevelStatements)] public class TopLevelStatementsTests : CompilingTestBase { private static CSharpParseOptions DefaultParseOptions => TestOptions.Regular9; private static bool IsNullableAnalysisEnabled(CSharpCompilation compilation) { var type = compilation.GlobalNamespace.GetMembers().OfType<SimpleProgramNamedTypeSymbol>().Single(); var methods = type.GetMembers().OfType<SynthesizedSimpleProgramEntryPointSymbol>(); return methods.Any(m => m.IsNullableAnalysisEnabled()); } [Fact] public void Simple_01() { var text = @"System.Console.WriteLine(""Hi!"");"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); Assert.True(entryPoint.ReturnsVoid); AssertEntryPointParameter(entryPoint); CompileAndVerify(comp, expectedOutput: "Hi!"); Assert.Same(entryPoint, comp.GetEntryPoint(default)); Assert.False(entryPoint.CanBeReferencedByName); Assert.False(entryPoint.ContainingType.CanBeReferencedByName); Assert.Equal("<Main>$", entryPoint.Name); Assert.Equal("<Program>$", entryPoint.ContainingType.Name); } private static void AssertEntryPointParameter(SynthesizedSimpleProgramEntryPointSymbol entryPoint) { Assert.Equal(1, entryPoint.ParameterCount); ParameterSymbol parameter = entryPoint.Parameters.Single(); Assert.Equal("System.String[] args", parameter.ToTestDisplayString(includeNonNullable: true)); Assert.True(parameter.IsImplicitlyDeclared); Assert.Same(entryPoint, parameter.ContainingSymbol); } [Fact] public void Simple_02() { var text = @" using System; using System.Threading.Tasks; Console.Write(""hello ""); await Task.Factory.StartNew(() => 5); Console.Write(""async main""); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); AssertEntryPointParameter(entryPoint); CompileAndVerify(comp, expectedOutput: "hello async main"); } [Fact] public void Simple_03() { var text1 = @" System.Console.Write(""1""); "; var text2 = @" // System.Console.Write(""2""); System.Console.WriteLine(); System.Console.WriteLine(); "; var text3 = @" // // System.Console.Write(""3""); System.Console.WriteLine(); System.Console.WriteLine(); "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,1): error CS8802: Only one compilation unit can have top-level statements. // System.Console.Write("2"); Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "System").WithLocation(3, 1) ); comp = CreateCompilation(new[] { text1, text2, text3 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,1): error CS8802: Only one compilation unit can have top-level statements. // System.Console.Write("2"); Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "System").WithLocation(3, 1), // (4,1): error CS8802: Only one compilation unit can have top-level statements. // System.Console.Write("3"); Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "System").WithLocation(4, 1) ); } [Fact] public void Simple_04() { var text = @" Type.M(); static class Type { public static void M() { System.Console.WriteLine(""Hi!""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void Simple_05() { var text1 = @" Type.M(); "; var text2 = @" static class Type { public static void M() { System.Console.WriteLine(""Hi!""); } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); comp = CreateCompilation(new[] { text2, text1 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void Simple_06_01() { var text1 = @" local(); void local() => System.Console.WriteLine(2); "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "2"); verifyModel(comp, comp.SyntaxTrees[0]); comp = CreateCompilation(text1, options: TestOptions.DebugExe.WithNullableContextOptions(NullableContextOptions.Enable), parseOptions: DefaultParseOptions); verifyModel(comp, comp.SyntaxTrees[0], nullableEnabled: true); static void verifyModel(CSharpCompilation comp, SyntaxTree tree1, bool nullableEnabled = false) { Assert.Equal(nullableEnabled, IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var model1 = comp.GetSemanticModel(tree1); verifyModelForGlobalStatements(tree1, model1); var unit1 = (CompilationUnitSyntax)tree1.GetRoot(); var localRef = unit1.DescendantNodes().OfType<IdentifierNameSyntax>().First(); var refSymbol = model1.GetSymbolInfo(localRef).Symbol; Assert.Equal("void local()", refSymbol.ToTestDisplayString()); Assert.Contains(refSymbol.Name, model1.LookupNames(localRef.SpanStart)); Assert.Contains(refSymbol, model1.LookupSymbols(localRef.SpanStart)); Assert.Same(refSymbol, model1.LookupSymbols(localRef.SpanStart, name: refSymbol.Name).Single()); var operation1 = model1.GetOperation(localRef.Parent); Assert.NotNull(operation1); Assert.IsAssignableFrom<IInvocationOperation>(operation1); Assert.NotNull(ControlFlowGraph.Create((IMethodBodyOperation)((IBlockOperation)operation1.Parent.Parent).Parent)); model1.VerifyOperationTree(unit1, @" IMethodBodyOperation (OperationKind.MethodBody, Type: null) (Syntax: 'local(); ... iteLine(2);') BlockBody: IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'local(); ... iteLine(2);') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'local();') Expression: IInvocationOperation (void local()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'local()') Instance Receiver: null Arguments(0) ILocalFunctionOperation (Symbol: void local()) (OperationKind.LocalFunction, Type: null) (Syntax: 'void local( ... iteLine(2);') IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '=> System.C ... riteLine(2)') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'System.Cons ... riteLine(2)') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(2)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '=> System.C ... riteLine(2)') ReturnedValue: null ExpressionBody: null "); var localDecl = unit1.DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Same(declSymbol.ContainingSymbol, model1.GetDeclaredSymbol(unit1)); Assert.Same(declSymbol.ContainingSymbol, model1.GetDeclaredSymbol((SyntaxNode)unit1)); Assert.Same(refSymbol, declSymbol); Assert.Contains(declSymbol.Name, model1.LookupNames(localDecl.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localDecl.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: declSymbol.Name).Single()); var operation2 = model1.GetOperation(localDecl); Assert.NotNull(operation2); Assert.IsAssignableFrom<ILocalFunctionOperation>(operation2); static void verifyModelForGlobalStatements(SyntaxTree tree1, SemanticModel model1) { var symbolInfo = model1.GetSymbolInfo(tree1.GetRoot()); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); var typeInfo = model1.GetTypeInfo(tree1.GetRoot()); Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); foreach (var globalStatement in tree1.GetRoot().DescendantNodes().OfType<GlobalStatementSyntax>()) { symbolInfo = model1.GetSymbolInfo(globalStatement); Assert.Null(model1.GetOperation(globalStatement)); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); typeInfo = model1.GetTypeInfo(globalStatement); Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); } } } } [Fact] public void Simple_06_02() { var text1 = @"local();"; var text2 = @"void local() => System.Console.WriteLine(2);"; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS8802: Only one compilation unit can have top-level statements. // void local() => System.Console.WriteLine(2); Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "void").WithLocation(1, 1), // (1,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(1, 1), // (1,6): warning CS8321: The local function 'local' is declared but never used // void local() => System.Console.WriteLine(2); Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(1, 6) ); verifyModel(comp, comp.SyntaxTrees[0], comp.SyntaxTrees[1]); comp = CreateCompilation(new[] { text2, text1 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS8802: Only one compilation unit can have top-level statements. // local(); Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "local").WithLocation(1, 1), // (1,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(1, 1), // (1,6): warning CS8321: The local function 'local' is declared but never used // void local() => System.Console.WriteLine(2); Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(1, 6) ); verifyModel(comp, comp.SyntaxTrees[1], comp.SyntaxTrees[0]); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe.WithNullableContextOptions(NullableContextOptions.Enable), parseOptions: DefaultParseOptions); verifyModel(comp, comp.SyntaxTrees[0], comp.SyntaxTrees[1], nullableEnabled: true); static void verifyModel(CSharpCompilation comp, SyntaxTree tree1, SyntaxTree tree2, bool nullableEnabled = false) { Assert.Equal(nullableEnabled, IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var model1 = comp.GetSemanticModel(tree1); verifyModelForGlobalStatements(tree1, model1); var unit1 = (CompilationUnitSyntax)tree1.GetRoot(); var localRef = unit1.DescendantNodes().OfType<IdentifierNameSyntax>().Single(); var refSymbol = model1.GetSymbolInfo(localRef).Symbol; var refMethod = model1.GetDeclaredSymbol(unit1); Assert.NotNull(refMethod); Assert.Null(refSymbol); var name = localRef.Identifier.ValueText; Assert.DoesNotContain(name, model1.LookupNames(localRef.SpanStart)); Assert.Empty(model1.LookupSymbols(localRef.SpanStart).Where(s => s.Name == name)); Assert.Empty(model1.LookupSymbols(localRef.SpanStart, name: name)); var operation1 = model1.GetOperation(localRef.Parent); Assert.NotNull(operation1); Assert.IsAssignableFrom<IInvalidOperation>(operation1); Assert.NotNull(ControlFlowGraph.Create((IMethodBodyOperation)((IBlockOperation)operation1.Parent.Parent).Parent)); model1.VerifyOperationTree(unit1, @" IMethodBodyOperation (OperationKind.MethodBody, Type: null, IsInvalid) (Syntax: 'local();') BlockBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'local();') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'local();') Expression: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'local()') Children(1): IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'local') Children(0) ExpressionBody: null "); SyntaxTreeSemanticModel syntaxTreeModel = ((SyntaxTreeSemanticModel)model1); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[unit1]; var model2 = comp.GetSemanticModel(tree2); verifyModelForGlobalStatements(tree2, model2); var unit2 = (CompilationUnitSyntax)tree2.GetRoot(); var declMethod = model2.GetDeclaredSymbol(unit2); var localDecl = unit2.DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single(); var declSymbol = model2.GetDeclaredSymbol(localDecl); Assert.Equal("void local()", declSymbol.ToTestDisplayString()); Assert.Same(declSymbol.ContainingSymbol, declMethod); Assert.NotEqual(refMethod, declMethod); Assert.Contains(declSymbol.Name, model2.LookupNames(localDecl.SpanStart)); Assert.Contains(declSymbol, model2.LookupSymbols(localDecl.SpanStart)); Assert.Same(declSymbol, model2.LookupSymbols(localDecl.SpanStart, name: declSymbol.Name).Single()); var operation2 = model2.GetOperation(localDecl); Assert.NotNull(operation2); Assert.IsAssignableFrom<ILocalFunctionOperation>(operation2); Assert.NotNull(ControlFlowGraph.Create((IMethodBodyOperation)((IBlockOperation)operation2.Parent).Parent)); var isInvalid = comp.SyntaxTrees[1] == tree2 ? ", IsInvalid" : ""; model2.VerifyOperationTree(unit2, @" IMethodBodyOperation (OperationKind.MethodBody, Type: null" + isInvalid + @") (Syntax: 'void local( ... iteLine(2);') BlockBody: IBlockOperation (1 statements) (OperationKind.Block, Type: null" + isInvalid + @", IsImplicit) (Syntax: 'void local( ... iteLine(2);') ILocalFunctionOperation (Symbol: void local()) (OperationKind.LocalFunction, Type: null" + isInvalid + @") (Syntax: 'void local( ... iteLine(2);') IBlockOperation (2 statements) (OperationKind.Block, Type: null) (Syntax: '=> System.C ... riteLine(2)') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'System.Cons ... riteLine(2)') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... riteLine(2)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '=> System.C ... riteLine(2)') ReturnedValue: null ExpressionBody: null "); static void verifyModelForGlobalStatements(SyntaxTree tree1, SemanticModel model1) { var symbolInfo = model1.GetSymbolInfo(tree1.GetRoot()); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); var typeInfo = model1.GetTypeInfo(tree1.GetRoot()); Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); foreach (var globalStatement in tree1.GetRoot().DescendantNodes().OfType<GlobalStatementSyntax>()) { symbolInfo = model1.GetSymbolInfo(globalStatement); Assert.Null(model1.GetOperation(globalStatement)); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); typeInfo = model1.GetTypeInfo(globalStatement); Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); } } } } [Fact] public void Simple_07() { var text1 = @" var i = 1; local(); "; var text2 = @" void local() => System.Console.WriteLine(i); "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // void local() => System.Console.WriteLine(i); Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "void").WithLocation(2, 1), // (2,5): warning CS0219: The variable 'i' is assigned but its value is never used // var i = 1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(2, 5), // (2,6): warning CS8321: The local function 'local' is declared but never used // void local() => System.Console.WriteLine(i); Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(2, 6), // (2,42): error CS0103: The name 'i' does not exist in the current context // void local() => System.Console.WriteLine(i); Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(2, 42), // (3,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(3, 1) ); verifyModel(comp, comp.SyntaxTrees[0], comp.SyntaxTrees[1]); comp = CreateCompilation(new[] { text2, text1 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // var i = 1; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "var").WithLocation(2, 1), // (2,5): warning CS0219: The variable 'i' is assigned but its value is never used // var i = 1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(2, 5), // (2,6): warning CS8321: The local function 'local' is declared but never used // void local() => System.Console.WriteLine(i); Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(2, 6), // (2,42): error CS0103: The name 'i' does not exist in the current context // void local() => System.Console.WriteLine(i); Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(2, 42), // (3,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(3, 1) ); verifyModel(comp, comp.SyntaxTrees[1], comp.SyntaxTrees[0]); static void verifyModel(CSharpCompilation comp, SyntaxTree tree1, SyntaxTree tree2) { Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.Int32 i", declSymbol.ToTestDisplayString()); Assert.Contains(declSymbol.Name, model1.LookupNames(localDecl.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localDecl.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: declSymbol.Name).Single()); Assert.NotNull(model1.GetOperation(tree1.GetRoot())); var operation1 = model1.GetOperation(localDecl); Assert.NotNull(operation1); Assert.IsAssignableFrom<IVariableDeclaratorOperation>(operation1); var localFuncRef = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "local").Single(); Assert.Contains(declSymbol.Name, model1.LookupNames(localFuncRef.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localFuncRef.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localFuncRef.SpanStart, name: declSymbol.Name).Single()); Assert.DoesNotContain(declSymbol, model1.AnalyzeDataFlow(localDecl.Ancestors().OfType<StatementSyntax>().First()).DataFlowsOut); var model2 = comp.GetSemanticModel(tree2); var localRef = tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "i").Single(); var refSymbol = model2.GetSymbolInfo(localRef).Symbol; Assert.Null(refSymbol); var name = localRef.Identifier.ValueText; Assert.DoesNotContain(name, model2.LookupNames(localRef.SpanStart)); Assert.Empty(model2.LookupSymbols(localRef.SpanStart).Where(s => s.Name == name)); Assert.Empty(model2.LookupSymbols(localRef.SpanStart, name: name)); Assert.NotNull(model2.GetOperation(tree2.GetRoot())); var operation2 = model2.GetOperation(localRef); Assert.NotNull(operation2); Assert.IsAssignableFrom<IInvalidOperation>(operation2); Assert.DoesNotContain(declSymbol, model2.AnalyzeDataFlow(localRef).DataFlowsIn); } } [Fact] public void Simple_08() { var text1 = @" var i = 1; System.Console.Write(i++); System.Console.Write(i); "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "12"); var tree1 = comp.SyntaxTrees[0]; Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.Int32 i", declSymbol.ToTestDisplayString()); Assert.Contains(declSymbol.Name, model1.LookupNames(localDecl.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localDecl.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: declSymbol.Name).Single()); var localRefs = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "i").ToArray(); Assert.Equal(2, localRefs.Length); foreach (var localRef in localRefs) { var refSymbol = model1.GetSymbolInfo(localRef).Symbol; Assert.Same(declSymbol, refSymbol); Assert.Contains(declSymbol.Name, model1.LookupNames(localRef.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localRef.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localRef.SpanStart, name: declSymbol.Name).Single()); } } [Fact] public void Simple_09() { var text1 = @" var i = 1; local(); void local() => System.Console.WriteLine(i); "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "1"); verifyModel(comp, comp.SyntaxTrees[0]); static void verifyModel(CSharpCompilation comp, SyntaxTree tree1) { Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.Int32 i", declSymbol.ToTestDisplayString()); Assert.Contains(declSymbol.Name, model1.LookupNames(localDecl.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localDecl.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: declSymbol.Name).Single()); Assert.NotNull(model1.GetOperation(tree1.GetRoot())); var operation1 = model1.GetOperation(localDecl); Assert.NotNull(operation1); Assert.IsAssignableFrom<IVariableDeclaratorOperation>(operation1); var localFuncRef = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "local").Single(); Assert.Contains(declSymbol.Name, model1.LookupNames(localFuncRef.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localFuncRef.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localFuncRef.SpanStart, name: declSymbol.Name).Single()); Assert.Contains(declSymbol, model1.AnalyzeDataFlow(localDecl.Ancestors().OfType<StatementSyntax>().First()).DataFlowsOut); var localRef = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "i").Single(); var refSymbol = model1.GetSymbolInfo(localRef).Symbol; Assert.Same(declSymbol, refSymbol); Assert.Contains(refSymbol.Name, model1.LookupNames(localRef.SpanStart)); Assert.Contains(refSymbol, model1.LookupSymbols(localRef.SpanStart)); Assert.Same(refSymbol, model1.LookupSymbols(localRef.SpanStart, name: refSymbol.Name).Single()); var operation2 = model1.GetOperation(localRef); Assert.NotNull(operation2); Assert.IsAssignableFrom<ILocalReferenceOperation>(operation2); // The following assert fails due to https://github.com/dotnet/roslyn/issues/41853, enable once the issue is fixed. //Assert.Contains(declSymbol, model1.AnalyzeDataFlow(localRef).DataFlowsIn); } } [Fact] public void LanguageVersion_01() { var text = @"System.Console.WriteLine(""Hi!"");"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (1,1): error CS8400: Feature 'top-level statements' is not available in C# 8.0. Please use language version 9.0 or greater. // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, @"System.Console.WriteLine(""Hi!"");").WithArguments("top-level statements", "9.0").WithLocation(1, 1) ); } [Fact] public void WithinType_01() { var text = @" class Test { System.Console.WriteLine(""Hi!""); } "; var comp = CreateCompilation(text, parseOptions: DefaultParseOptions); var expected = new[] { // (4,29): error CS1519: Invalid token '(' in class, record, struct, or interface member declaration // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "(").WithArguments("(").WithLocation(4, 29), // (4,30): error CS1031: Type expected // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_TypeExpected, @"""Hi!""").WithLocation(4, 30), // (4,30): error CS8124: Tuple must contain at least two elements. // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_TupleTooFewElements, @"""Hi!""").WithLocation(4, 30), // (4,30): error CS1026: ) expected // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_CloseParenExpected, @"""Hi!""").WithLocation(4, 30), // (4,30): error CS1519: Invalid token '"Hi!"' in class, record, struct, or interface member declaration // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, @"""Hi!""").WithArguments(@"""Hi!""").WithLocation(4, 30) }; comp.GetDiagnostics(CompilationStage.Parse, includeEarlierStages: false, cancellationToken: default).Verify(expected); comp.VerifyDiagnostics(expected); } [Fact] public void WithinNamespace_01() { var text = @" namespace Test { System.Console.WriteLine(""Hi!""); } "; var comp = CreateCompilation(text, parseOptions: DefaultParseOptions); var expected = new[] { // (4,20): error CS0116: A namespace cannot directly contain members such as fields or methods // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "WriteLine").WithLocation(4, 20), // (4,30): error CS1026: ) expected // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_CloseParenExpected, @"""Hi!""").WithLocation(4, 30), // (4,30): error CS1022: Type or namespace definition, or end-of-file expected // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_EOFExpected, @"""Hi!""").WithLocation(4, 30) }; comp.GetDiagnostics(CompilationStage.Parse, includeEarlierStages: false, cancellationToken: default).Verify(expected); comp.VerifyDiagnostics(expected); } [Fact] public void LocalDeclarationStatement_01() { var text = @" string s = ""Hi!""; System.Console.WriteLine(s); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var reference = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "s").Single(); var local = model.GetDeclaredSymbol(declarator); Assert.Same(local, model.GetSymbolInfo(reference).Symbol); Assert.Equal("System.String s", local.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, local.Kind); Assert.Equal(SymbolKind.Method, local.ContainingSymbol.Kind); Assert.False(local.ContainingSymbol.IsImplicitlyDeclared); Assert.Equal(SymbolKind.NamedType, local.ContainingSymbol.ContainingSymbol.Kind); Assert.False(local.ContainingSymbol.ContainingSymbol.IsImplicitlyDeclared); Assert.True(((INamespaceSymbol)local.ContainingSymbol.ContainingSymbol.ContainingSymbol).IsGlobalNamespace); } [Fact] public void LocalDeclarationStatement_02() { var text = @" new string a = ""Hi!""; System.Console.WriteLine(a); public string b = ""Hi!""; System.Console.WriteLine(b); static string c = ""Hi!""; System.Console.WriteLine(c); readonly string d = ""Hi!""; System.Console.WriteLine(d); volatile string e = ""Hi!""; System.Console.WriteLine(e); [System.Obsolete()] string f = ""Hi!""; System.Console.WriteLine(f); [System.Obsolete()] const string g = ""Hi!""; System.Console.WriteLine(g); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,12): error CS0116: A namespace cannot directly contain members such as fields or methods // new string a = "Hi!"; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "a").WithLocation(2, 12), // (2,12): warning CS0109: The member '<invalid-global-code>.a' does not hide an accessible member. The new keyword is not required. // new string a = "Hi!"; Diagnostic(ErrorCode.WRN_NewNotRequired, "a").WithArguments("<invalid-global-code>.a").WithLocation(2, 12), // (3,26): error CS0103: The name 'a' does not exist in the current context // System.Console.WriteLine(a); Diagnostic(ErrorCode.ERR_NameNotInContext, "a").WithArguments("a").WithLocation(3, 26), // (4,15): error CS0116: A namespace cannot directly contain members such as fields or methods // public string b = "Hi!"; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "b").WithLocation(4, 15), // (5,26): error CS0103: The name 'b' does not exist in the current context // System.Console.WriteLine(b); Diagnostic(ErrorCode.ERR_NameNotInContext, "b").WithArguments("b").WithLocation(5, 26), // (6,1): error CS0106: The modifier 'static' is not valid for this item // static string c = "Hi!"; Diagnostic(ErrorCode.ERR_BadMemberFlag, "static").WithArguments("static").WithLocation(6, 1), // (8,1): error CS0106: The modifier 'readonly' is not valid for this item // readonly string d = "Hi!"; Diagnostic(ErrorCode.ERR_BadMemberFlag, "readonly").WithArguments("readonly").WithLocation(8, 1), // (10,1): error CS0106: The modifier 'volatile' is not valid for this item // volatile string e = "Hi!"; Diagnostic(ErrorCode.ERR_BadMemberFlag, "volatile").WithArguments("volatile").WithLocation(10, 1), // (12,1): error CS7014: Attributes are not valid in this context. // [System.Obsolete()] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[System.Obsolete()]").WithLocation(12, 1), // (15,1): error CS7014: Attributes are not valid in this context. // [System.Obsolete()] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[System.Obsolete()]").WithLocation(15, 1) ); } [Fact] public void LocalDeclarationStatement_03() { var text = @" string a = ""1""; string a = ""2""; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,8): warning CS0219: The variable 'a' is assigned but its value is never used // string a = "1"; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(2, 8), // (3,8): error CS0128: A local variable or function named 'a' is already defined in this scope // string a = "2"; Diagnostic(ErrorCode.ERR_LocalDuplicate, "a").WithArguments("a").WithLocation(3, 8), // (3,8): warning CS0219: The variable 'a' is assigned but its value is never used // string a = "2"; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(3, 8) ); } [Fact] public void LocalDeclarationStatement_04() { var text = @" using System; using System.Threading.Tasks; var s = await local(); System.Console.WriteLine(s); async Task<string> local() { await Task.Factory.StartNew(() => 5); return ""Hi!""; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void LocalDeclarationStatement_05() { var text = @" const string s = ""Hi!""; System.Console.WriteLine(s); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void LocalDeclarationStatement_06() { var text = @" a.ToString(); string a = ""2""; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS0841: Cannot use local variable 'a' before it is declared // a.ToString(); Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "a").WithArguments("a").WithLocation(2, 1) ); } [Fact] public void LocalDeclarationStatement_07() { var text1 = @" string x = ""1""; System.Console.Write(x); "; var text2 = @" int x = 1; System.Console.Write(x); "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // int x = 1; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "int").WithLocation(2, 1) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var symbol1 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single()); Assert.Equal("System.String x", symbol1.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Single()).Symbol); var tree2 = comp.SyntaxTrees[1]; var model2 = comp.GetSemanticModel(tree2); var symbol2 = model2.GetDeclaredSymbol(tree2.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single()); Assert.Equal("System.Int32 x", symbol2.ToTestDisplayString()); Assert.Same(symbol2, model2.GetSymbolInfo(tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Single()).Symbol); } [Fact] public void LocalDeclarationStatement_08() { var text = @" int a = 0; int b = 0; int c = -100; ref int d = ref c; d = 300; d = ref local(true, ref a, ref b); d = 100; d = ref local(false, ref a, ref b); d = 200; System.Console.Write(a); System.Console.Write(' '); System.Console.Write(b); System.Console.Write(' '); System.Console.Write(c); ref int local(bool flag, ref int a, ref int b) { return ref flag ? ref a : ref b; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "100 200 300", verify: Verification.Skipped); } [Fact] public void LocalDeclarationStatement_09() { var text = @" using var a = new MyDisposable(); System.Console.Write(1); class MyDisposable : System.IDisposable { public void Dispose() { System.Console.Write(2); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "12", verify: Verification.Skipped); } [Fact] public void LocalDeclarationStatement_10() { string source = @" await using var x = new C(); System.Console.Write(""body ""); class C : System.IAsyncDisposable, System.IDisposable { public System.Threading.Tasks.ValueTask DisposeAsync() { System.Console.Write(""DisposeAsync""); return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask); } public void Dispose() { System.Console.Write(""IGNORED""); } } "; var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "body DisposeAsync"); } [Fact] public void LocalDeclarationStatement_11() { var text1 = @" string x = ""1""; System.Console.Write(x); int x = 1; System.Console.Write(x); "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,5): error CS0128: A local variable or function named 'x' is already defined in this scope // int x = 1; Diagnostic(ErrorCode.ERR_LocalDuplicate, "x").WithArguments("x").WithLocation(4, 5), // (4,5): warning CS0219: The variable 'x' is assigned but its value is never used // int x = 1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(4, 5) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var symbol1 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First()); Assert.Equal("System.String x", symbol1.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").First()).Symbol); var symbol2 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Skip(1).Single()); Assert.Equal("System.Int32 x", symbol2.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Skip(1).Single()).Symbol); } [Fact] public void LocalDeclarationStatement_12() { var text = @" (int x, int y) = (1, 2); System.Console.WriteLine(x+y); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "3"); } [Fact] public void LocalDeclarationStatement_13() { var text = @" var (x, y) = (1, 2); System.Console.WriteLine(x+y); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "3"); } [Fact] public void LocalDeclarationStatement_14() { var text1 = @" string args = ""1""; System.Console.Write(args); "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,8): error CS0136: A local or parameter named 'args' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // string args = "1"; Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "args").WithArguments("args").WithLocation(2, 8) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var symbol1 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First()); Assert.Equal("System.String args", symbol1.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "args").Single()).Symbol); } [Fact] public void LocalDeclarationStatement_15() { var text1 = @" using System.Linq; string x = null; _ = from x in new object[0] select x; System.Console.Write(x); "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,10): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x' // _ = from x in new object[0] select x; Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(4, 10) ); } [Fact] public void LocalDeclarationStatement_16() { var text = @" System.Console.WriteLine(); string await = ""Hi!""; System.Console.WriteLine(await); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,8): error CS4003: 'await' cannot be used as an identifier within an async method or lambda expression // string await = "Hi!"; Diagnostic(ErrorCode.ERR_BadAwaitAsIdentifier, "await").WithLocation(3, 8), // (3,8): warning CS0219: The variable 'await' is assigned but its value is never used // string await = "Hi!"; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "await").WithArguments("await").WithLocation(3, 8), // (4,31): error CS1525: Invalid expression term ')' // System.Console.WriteLine(await); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(4, 31) ); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnType.IsErrorType()); AssertEntryPointParameter(entryPoint); } [Fact] public void LocalDeclarationStatement_17() { var text = @" string async = ""Hi!""; System.Console.WriteLine(async); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void LocalDeclarationStatement_18() { var text = @" int c = -100; ref int d = ref c; System.Console.Write(d); await System.Threading.Tasks.Task.Yield(); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,9): error CS8177: Async methods cannot have by-reference locals // ref int d = ref c; Diagnostic(ErrorCode.ERR_BadAsyncLocalType, "d").WithLocation(3, 9) ); } [Fact] public void UsingStatement_01() { string source = @" await using (var x = new C()) { System.Console.Write(""body ""); } class C : System.IAsyncDisposable, System.IDisposable { public System.Threading.Tasks.ValueTask DisposeAsync() { System.Console.Write(""DisposeAsync""); return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask); } public void Dispose() { System.Console.Write(""IGNORED""); } } "; var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "body DisposeAsync"); } [Fact] public void UsingStatement_02() { string source = @" await using (new C()) { System.Console.Write(""body ""); } class C : System.IAsyncDisposable, System.IDisposable { public System.Threading.Tasks.ValueTask DisposeAsync() { System.Console.Write(""DisposeAsync""); return new System.Threading.Tasks.ValueTask(System.Threading.Tasks.Task.CompletedTask); } public void Dispose() { System.Console.Write(""IGNORED""); } } "; var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "body DisposeAsync"); } [Fact] public void UsingStatement_03() { string source = @" using (new C()) { System.Console.Write(""body ""); } class C : System.IDisposable { public void Dispose() { System.Console.Write(""Dispose""); } } "; var comp = CreateCompilationWithTasksExtensions(new[] { source, IAsyncDisposableDefinition }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "body Dispose"); } [Fact] public void ForeachStatement_01() { string source = @" using System.Threading.Tasks; await foreach (var i in new C()) { } System.Console.Write(""Done""); class C { public Enumerator GetAsyncEnumerator() { return new Enumerator(); } public sealed class Enumerator { public async Task<bool> MoveNextAsync() { System.Console.Write(""MoveNextAsync ""); await Task.Yield(); return false; } public int Current { get => throw null; } public async Task DisposeAsync() { System.Console.Write(""DisposeAsync ""); await Task.Yield(); } } } "; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "MoveNextAsync DisposeAsync Done"); } [Fact] public void ForeachStatement_02() { var text = @" int i = 0; foreach (var j in new [] {2, 3}) { i += j; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "5"); } [Fact] public void ForeachStatement_03() { var text = @" int i = 0; foreach (var (j, k) in new [] {(2,200), (3,300)}) { i += j; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "5"); } [Fact] public void LocalUsedBeforeDeclaration_01() { var text1 = @" const string x = y; System.Console.Write(x); "; var text2 = @" const string y = x; System.Console.Write(y); "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // const string y = x; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "const").WithLocation(2, 1), // (2,18): error CS0103: The name 'y' does not exist in the current context // const string x = y; Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(2, 18), // (2,18): error CS0103: The name 'x' does not exist in the current context // const string y = x; Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(2, 18) ); comp = CreateCompilation(new[] { "System.Console.WriteLine();", text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // const string x = y; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "const").WithLocation(2, 1), // (2,1): error CS8802: Only one compilation unit can have top-level statements. // const string y = x; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "const").WithLocation(2, 1), // (2,18): error CS0103: The name 'y' does not exist in the current context // const string x = y; Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(2, 18), // (2,18): error CS0103: The name 'x' does not exist in the current context // const string y = x; Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(2, 18) ); } [Fact] public void LocalUsedBeforeDeclaration_02() { var text1 = @" var x = y; System.Console.Write(x); "; var text2 = @" var y = x; System.Console.Write(y); "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // var y = x; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "var").WithLocation(2, 1), // (2,9): error CS0103: The name 'y' does not exist in the current context // var x = y; Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(2, 9), // (2,9): error CS0103: The name 'x' does not exist in the current context // var y = x; Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(2, 9) ); comp = CreateCompilation(new[] { "System.Console.WriteLine();", text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // var x = y; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "var").WithLocation(2, 1), // (2,1): error CS8802: Only one compilation unit can have top-level statements. // var y = x; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "var").WithLocation(2, 1), // (2,9): error CS0103: The name 'y' does not exist in the current context // var x = y; Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(2, 9), // (2,9): error CS0103: The name 'x' does not exist in the current context // var y = x; Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(2, 9) ); } [Fact] public void LocalUsedBeforeDeclaration_03() { var text1 = @" string x = ""x""; System.Console.Write(x); "; var text2 = @" class C1 { void Test() { System.Console.Write(x); } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,30): error CS8801: Cannot use local variable or local function 'x' declared in a top-level statement in this context. // System.Console.Write(x); Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "x").WithArguments("x").WithLocation(6, 30) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree2 = comp.SyntaxTrees[1]; var model2 = comp.GetSemanticModel(tree2); var nameRef = tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Single(); var symbol2 = model2.GetSymbolInfo(nameRef).Symbol; Assert.Equal("System.String x", symbol2.ToTestDisplayString()); Assert.Equal("System.String", model2.GetTypeInfo(nameRef).Type.ToTestDisplayString()); Assert.Null(model2.GetOperation(tree2.GetRoot())); comp = CreateCompilation(new[] { text2, text1 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,30): error CS8801: Cannot use local variable or local function 'x' declared in a top-level statement in this context. // System.Console.Write(x); Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "x").WithArguments("x").WithLocation(6, 30) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel tree2 = comp.SyntaxTrees[0]; model2 = comp.GetSemanticModel(tree2); nameRef = tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Single(); symbol2 = model2.GetSymbolInfo(nameRef).Symbol; Assert.Equal("System.String x", symbol2.ToTestDisplayString()); Assert.Equal("System.String", model2.GetTypeInfo(nameRef).Type.ToTestDisplayString()); Assert.Null(model2.GetOperation(tree2.GetRoot())); } [Fact] public void LocalUsedBeforeDeclaration_04() { var text1 = @" string x = ""x""; local(); "; var text2 = @" void local() { System.Console.Write(x); } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // void local() Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "void").WithLocation(2, 1), // (2,6): warning CS8321: The local function 'local' is declared but never used // void local() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(2, 6), // (2,8): warning CS0219: The variable 'x' is assigned but its value is never used // string x = "x"; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(2, 8), // (3,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(3, 1), // (4,26): error CS0103: The name 'x' does not exist in the current context // System.Console.Write(x); Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(4, 26) ); comp = CreateCompilation(new[] { text2, text1 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // string x = "x"; Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "string").WithLocation(2, 1), // (2,6): warning CS8321: The local function 'local' is declared but never used // void local() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(2, 6), // (2,8): warning CS0219: The variable 'x' is assigned but its value is never used // string x = "x"; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(2, 8), // (3,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(3, 1), // (4,26): error CS0103: The name 'x' does not exist in the current context // System.Console.Write(x); Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(4, 26) ); } [Fact] public void FlowAnalysis_01() { var text = @" #nullable enable string a = ""1""; string? b; System.Console.WriteLine(b); string? c = null; c.ToString(); d: System.Console.WriteLine(); string e() => ""1""; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,8): warning CS0219: The variable 'a' is assigned but its value is never used // string a = "1"; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "a").WithArguments("a").WithLocation(3, 8), // (5,26): error CS0165: Use of unassigned local variable 'b' // System.Console.WriteLine(b); Diagnostic(ErrorCode.ERR_UseDefViolation, "b").WithArguments("b").WithLocation(5, 26), // (7,1): warning CS8602: Dereference of a possibly null reference. // c.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(7, 1), // (8,1): warning CS0164: This label has not been referenced // d: System.Console.WriteLine(); Diagnostic(ErrorCode.WRN_UnreferencedLabel, "d").WithLocation(8, 1), // (9,8): warning CS8321: The local function 'e' is declared but never used // string e() => "1"; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "e").WithArguments("e").WithLocation(9, 8) ); var tree = comp.SyntaxTrees.Single(); var reference = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "c").Single(); var model1 = comp.GetSemanticModel(tree); Assert.Equal(CodeAnalysis.NullableFlowState.MaybeNull, model1.GetTypeInfo(reference).Nullability.FlowState); var model2 = comp.GetSemanticModel(tree); Assert.Equal(CodeAnalysis.NullableFlowState.MaybeNull, model1.GetTypeInfo(reference).Nullability.FlowState); } [Fact] public void FlowAnalysis_02() { var text = @" System.Console.WriteLine(); if (args.Length == 0) { return 10; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS0161: '<top-level-statements-entry-point>': not all code paths return a value // System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_ReturnExpected, @"System.Console.WriteLine(); if (args.Length == 0) { return 10; } ").WithArguments("<top-level-statements-entry-point>").WithLocation(2, 1) ); } [Fact] public void NullableRewrite_01() { var text1 = @" void local1() { System.Console.WriteLine(""local1 - "" + s); } "; var text2 = @" using System; string s = ""Hello world!""; foreach (var c in s) { Console.Write(c); } goto label1; label1: Console.WriteLine(); local1(); local2(); "; var text3 = @" void local2() { System.Console.WriteLine(""local2 - "" + s); } "; var comp = CreateCompilation(new[] { text1, text2, text3 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var tree = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree); foreach (var id in tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>()) { _ = model1.GetTypeInfo(id).Nullability; } var model2 = comp.GetSemanticModel(tree); foreach (var id in tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>()) { _ = model2.GetTypeInfo(id).Nullability; } } [Fact] public void Scope_01() { var text = @" using alias1 = Test; string Test = ""1""; System.Console.WriteLine(Test); class Test {} class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 5 Test.ToString(); // 6 Test.EndsWith(null); // 7 _ = nameof(Test); // 8 } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 20), // (34,38): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(34, 38), // (35,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 6 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(35, 13), // (36,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 7 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(36, 13), // (37,24): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 8 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(37, 24) ); var getHashCode = ((Compilation)comp).GetMember("System.Object." + nameof(GetHashCode)); var testType = ((Compilation)comp).GetTypeByMetadataName("Test"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.String Test", declSymbol.ToTestDisplayString()); var names = model1.LookupNames(localDecl.SpanStart); Assert.Contains(getHashCode.Name, names); var symbols = model1.LookupSymbols(localDecl.SpanStart); Assert.Contains(getHashCode, symbols); Assert.Same(getHashCode, model1.LookupSymbols(localDecl.SpanStart, name: getHashCode.Name).Single()); Assert.Contains("Test", names); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: "Test").Single()); symbols = model1.LookupNamespacesAndTypes(localDecl.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupNamespacesAndTypes(localDecl.SpanStart, name: "Test").Single()); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var nameRefs = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test").ToArray(); var nameRef = nameRefs[1]; Assert.Equal("System.Console.WriteLine(Test)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model1, nameRef); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); nameRef = nameRefs[0]; Assert.Equal("using alias1 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); names = model.LookupNames(nameRef.SpanStart); Assert.DoesNotContain(getHashCode.Name, names); Assert.Contains("Test", names); symbols = model.LookupSymbols(nameRef.SpanStart); Assert.DoesNotContain(getHashCode, symbols); Assert.Empty(model.LookupSymbols(nameRef.SpanStart, name: getHashCode.Name)); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); nameRef = nameRefs[2]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); Assert.DoesNotContain(getHashCode.Name, model.LookupNames(nameRef.SpanStart)); verifyModel(declSymbol, model, nameRef); nameRef = nameRefs[4]; Assert.Equal("System.Console.WriteLine(Test)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model, nameRef); nameRef = nameRefs[8]; Assert.Equal("using alias2 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model, nameRef); nameRef = nameRefs[9]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); Assert.DoesNotContain(getHashCode.Name, model.LookupNames(nameRef.SpanStart)); verifyModel(declSymbol, model, nameRef); nameRef = nameRefs[11]; Assert.Equal("System.Console.WriteLine(Test)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model, nameRef); void verifyModel(ISymbol declSymbol, SemanticModel model, IdentifierNameSyntax nameRef) { var names = model.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); var symbols = model.LookupSymbols(nameRef.SpanStart); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); symbols = model.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model.LookupNamespacesAndTypes(nameRef.SpanStart, name: "Test").Single()); } } [Fact] public void Scope_02() { var text1 = @" string Test = ""1""; System.Console.WriteLine(Test); "; var text2 = @" using alias1 = Test; class Test {} class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 5 Test.ToString(); // 6 Test.EndsWith(null); // 7 _ = nameof(Test); // 8 } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 20), // (31,38): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(31, 38), // (32,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 6 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(32, 13), // (33,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 7 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(33, 13), // (34,24): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 8 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(34, 24) ); var getHashCode = ((Compilation)comp).GetMember("System.Object." + nameof(GetHashCode)); var testType = ((Compilation)comp).GetTypeByMetadataName("Test"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.String Test", declSymbol.ToTestDisplayString()); var names = model1.LookupNames(localDecl.SpanStart); Assert.Contains(getHashCode.Name, names); var symbols = model1.LookupSymbols(localDecl.SpanStart); Assert.Contains(getHashCode, symbols); Assert.Same(getHashCode, model1.LookupSymbols(localDecl.SpanStart, name: getHashCode.Name).Single()); Assert.Contains("Test", names); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: "Test").Single()); symbols = model1.LookupNamespacesAndTypes(localDecl.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupNamespacesAndTypes(localDecl.SpanStart, name: "Test").Single()); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree2 = comp.SyntaxTrees[1]; var model2 = comp.GetSemanticModel(tree2); Assert.Null(model2.GetDeclaredSymbol((CompilationUnitSyntax)tree2.GetRoot())); var nameRefs = tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test").ToArray(); var nameRef = nameRefs[0]; Assert.Equal("using alias1 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); names = model2.LookupNames(nameRef.SpanStart); Assert.DoesNotContain(getHashCode.Name, names); Assert.Contains("Test", names); symbols = model2.LookupSymbols(nameRef.SpanStart); Assert.DoesNotContain(getHashCode, symbols); Assert.Empty(model2.LookupSymbols(nameRef.SpanStart, name: getHashCode.Name)); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model2.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); nameRef = nameRefs[1]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); Assert.DoesNotContain(getHashCode.Name, model2.LookupNames(nameRef.SpanStart)); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[3]; Assert.Equal("System.Console.WriteLine(Test)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[7]; Assert.Equal("using alias2 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[8]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); Assert.DoesNotContain(getHashCode.Name, model2.LookupNames(nameRef.SpanStart)); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[10]; Assert.Equal("System.Console.WriteLine(Test)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); void verifyModel(ISymbol declSymbol, SemanticModel model2, IdentifierNameSyntax nameRef) { var names = model2.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); var symbols = model2.LookupSymbols(nameRef.SpanStart); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model2.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); symbols = model2.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model2.LookupNamespacesAndTypes(nameRef.SpanStart, name: "Test").Single()); } } [Fact] public void Scope_03() { var text1 = @" string Test = ""1""; System.Console.WriteLine(Test); "; var text2 = @" class Test {} class Derived : Test { void M() { int Test = 0; System.Console.WriteLine(Test++); } } namespace N1 { class Derived : Test { void M() { int Test = 1; System.Console.WriteLine(Test++); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); comp = CreateCompilation(text1 + text2, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); Assert.Throws<System.ArgumentException>(() => CreateCompilation(new[] { Parse(text1, filename: "text1", DefaultParseOptions), Parse(text1, filename: "text2", TestOptions.Regular6) }, options: TestOptions.DebugExe)); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics( // (2,1): error CS8107: Feature 'top-level statements' is not available in C# 7.0. Please use language version 9.0 or greater. // string Test = "1"; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, @"string Test = ""1"";").WithArguments("top-level statements", "9.0").WithLocation(2, 1) ); } [Fact] public void Scope_04() { var text = @" using alias1 = Test; string Test() => ""1""; System.Console.WriteLine(Test()); class Test {} class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 6 Test().ToString(); // 7 Test().EndsWith(null); // 8 var d = new System.Func<string>(Test); // 9 d(); _ = nameof(Test); // 10 } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 33), // (21,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(21, 20), // (36,38): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 6 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(36, 38), // (37,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 7 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(37, 13), // (38,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 8 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(38, 13), // (39,45): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // var d = new System.Func<string>(Test); // 9 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(39, 45), // (41,24): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 10 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(41, 24) ); var testType = ((Compilation)comp).GetTypeByMetadataName("Test"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.String Test()", declSymbol.ToTestDisplayString()); var names = model1.LookupNames(localDecl.SpanStart); var symbols = model1.LookupSymbols(localDecl.SpanStart); Assert.Contains("Test", names); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: "Test").Single()); symbols = model1.LookupNamespacesAndTypes(localDecl.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupNamespacesAndTypes(localDecl.SpanStart, name: "Test").Single()); var nameRefs = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test").ToArray(); var nameRef = nameRefs[0]; Assert.Equal("using alias1 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); names = model1.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); symbols = model1.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); nameRef = nameRefs[2]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model1, nameRef); nameRef = nameRefs[4]; Assert.Equal("System.Console.WriteLine(Test())", nameRef.Parent.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model1, nameRef); nameRef = nameRefs[9]; Assert.Equal("using alias2 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model1, nameRef); nameRef = nameRefs[10]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model1, nameRef); nameRef = nameRefs[12]; Assert.Equal("System.Console.WriteLine(Test())", nameRef.Parent.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model1, nameRef); void verifyModel(ISymbol declSymbol, SemanticModel model2, IdentifierNameSyntax nameRef) { var names = model2.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); var symbols = model2.LookupSymbols(nameRef.SpanStart); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model2.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); symbols = model2.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model2.LookupNamespacesAndTypes(nameRef.SpanStart, name: "Test").Single()); } } [Fact] public void Scope_05() { var text1 = @" string Test() => ""1""; System.Console.WriteLine(Test()); "; var text2 = @" using alias1 = Test; class Test {} class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 6 Test().ToString(); // 7 Test().EndsWith(null); // 8 var d = new System.Func<string>(Test); // 9 d(); _ = nameof(Test); // 10 } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 33), // (18,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 20), // (33,38): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 6 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(33, 38), // (34,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 7 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(34, 13), // (35,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 8 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(35, 13), // (36,45): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // var d = new System.Func<string>(Test); // 9 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(36, 45), // (38,24): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 10 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(38, 24) ); var testType = ((Compilation)comp).GetTypeByMetadataName("Test"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.String Test()", declSymbol.ToTestDisplayString()); var names = model1.LookupNames(localDecl.SpanStart); var symbols = model1.LookupSymbols(localDecl.SpanStart); Assert.Contains("Test", names); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model1.LookupSymbols(localDecl.SpanStart, name: "Test").Single()); symbols = model1.LookupNamespacesAndTypes(localDecl.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupNamespacesAndTypes(localDecl.SpanStart, name: "Test").Single()); var tree2 = comp.SyntaxTrees[1]; var model2 = comp.GetSemanticModel(tree2); var nameRefs = tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test").ToArray(); var nameRef = nameRefs[0]; Assert.Equal("using alias1 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); names = model2.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); symbols = model2.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model2.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); nameRef = nameRefs[1]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[3]; Assert.Equal("System.Console.WriteLine(Test())", nameRef.Parent.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[8]; Assert.Equal("using alias2 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[9]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); nameRef = nameRefs[11]; Assert.Equal("System.Console.WriteLine(Test())", nameRef.Parent.Parent.Parent.Parent.ToString()); Assert.Same(declSymbol, model2.GetSymbolInfo(nameRef).Symbol); verifyModel(declSymbol, model2, nameRef); void verifyModel(ISymbol declSymbol, SemanticModel model2, IdentifierNameSyntax nameRef) { var names = model2.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); var symbols = model2.LookupSymbols(nameRef.SpanStart); Assert.DoesNotContain(testType, symbols); Assert.Contains(declSymbol, symbols); Assert.Same(declSymbol, model2.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); symbols = model2.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model2.LookupNamespacesAndTypes(nameRef.SpanStart, name: "Test").Single()); } } [Fact] public void Scope_06() { var text1 = @" string Test() => ""1""; System.Console.WriteLine(Test()); "; var text2 = @" class Test {} class Derived : Test { void M() { int Test() => 1; int x = Test() + 1; System.Console.WriteLine(x); } } namespace N1 { class Derived : Test { void M() { int Test() => 1; int x = Test() + 1; System.Console.WriteLine(x); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); comp = CreateCompilation(text1 + text2, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics( // (2,1): error CS8107: Feature 'top-level statements' is not available in C# 7.0. Please use language version 9.0 or greater. // string Test() => "1"; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, @"string Test() => ""1"";").WithArguments("top-level statements", "9.0").WithLocation(2, 1) ); } [Fact] public void Scope_07() { var text = @" using alias1 = Test; goto Test; Test: System.Console.WriteLine(""1""); class Test {} class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); goto Test; // 1 } } namespace N1 { using alias2 = Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); goto Test; // 2 } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (15,14): error CS0159: No such label 'Test' within the scope of the goto statement // goto Test; // 1 Diagnostic(ErrorCode.ERR_LabelNotFound, "Test").WithArguments("Test").WithLocation(15, 14), // (30,18): error CS0159: No such label 'Test' within the scope of the goto statement // goto Test; // 2 Diagnostic(ErrorCode.ERR_LabelNotFound, "Test").WithArguments("Test").WithLocation(30, 18) ); var testType = ((Compilation)comp).GetTypeByMetadataName("Test"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var labelDecl = tree1.GetRoot().DescendantNodes().OfType<LabeledStatementSyntax>().Single(); var declSymbol = model1.GetDeclaredSymbol(labelDecl); Assert.Equal("Test", declSymbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Label, declSymbol.Kind); var names = model1.LookupNames(labelDecl.SpanStart); var symbols = model1.LookupSymbols(labelDecl.SpanStart); Assert.Contains("Test", names); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupSymbols(labelDecl.SpanStart, name: "Test").Single()); symbols = model1.LookupNamespacesAndTypes(labelDecl.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupNamespacesAndTypes(labelDecl.SpanStart, name: "Test").Single()); Assert.Same(declSymbol, model1.LookupLabels(labelDecl.SpanStart).Single()); Assert.Same(declSymbol, model1.LookupLabels(labelDecl.SpanStart, name: "Test").Single()); var nameRefs = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test").ToArray(); var nameRef = nameRefs[0]; Assert.Equal("using alias1 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); names = model1.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); symbols = model1.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); Assert.Empty(model1.LookupLabels(nameRef.SpanStart)); Assert.Empty(model1.LookupLabels(nameRef.SpanStart, name: "Test")); nameRef = nameRefs[1]; Assert.Equal("goto Test;", nameRef.Parent.ToString()); Assert.Same(declSymbol, model1.GetSymbolInfo(nameRef).Symbol); names = model1.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); symbols = model1.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model1.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); Assert.Same(declSymbol, model1.LookupLabels(nameRef.SpanStart).Single()); Assert.Same(declSymbol, model1.LookupLabels(nameRef.SpanStart, name: "Test").Single()); nameRef = nameRefs[2]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(model1, nameRef); nameRef = nameRefs[4]; Assert.Equal("goto Test;", nameRef.Parent.ToString()); Assert.Null(model1.GetSymbolInfo(nameRef).Symbol); verifyModel(model1, nameRef); nameRef = nameRefs[5]; Assert.Equal("using alias2 = Test;", nameRef.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(model1, nameRef); nameRef = nameRefs[6]; Assert.Equal(": Test", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model1.GetSymbolInfo(nameRef).Symbol); verifyModel(model1, nameRef); nameRef = nameRefs[8]; Assert.Null(model1.GetSymbolInfo(nameRef).Symbol); Assert.Equal("goto Test;", nameRef.Parent.ToString()); verifyModel(model1, nameRef); void verifyModel(SemanticModel model2, IdentifierNameSyntax nameRef) { var names = model2.LookupNames(nameRef.SpanStart); Assert.Contains("Test", names); var symbols = model2.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model2.LookupSymbols(nameRef.SpanStart, name: "Test").Single()); symbols = model2.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model2.LookupNamespacesAndTypes(nameRef.SpanStart, name: "Test").Single()); Assert.Empty(model2.LookupLabels(nameRef.SpanStart)); Assert.Empty(model2.LookupLabels(nameRef.SpanStart, name: "Test")); } } [Fact] public void Scope_08() { var text = @" goto Test; Test: System.Console.WriteLine(""1""); class Test {} class Derived : Test { void M() { goto Test; Test: System.Console.WriteLine(); } } namespace N1 { class Derived : Test { void M() { goto Test; Test: System.Console.WriteLine(); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); } [Fact] public void Scope_09() { var text = @" string Test = ""1""; System.Console.WriteLine(Test); new void M() { int Test = 0; System.Console.WriteLine(Test++); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (5,10): error CS0116: A namespace cannot directly contain members such as fields or methods // new void M() Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "M").WithLocation(5, 10), // (5,10): warning CS0109: The member '<invalid-global-code>.M()' does not hide an accessible member. The new keyword is not required. // new void M() Diagnostic(ErrorCode.WRN_NewNotRequired, "M").WithArguments("<invalid-global-code>.M()").WithLocation(5, 10) ); } [Fact] public void Scope_10() { var text = @" string Test = ""1""; System.Console.WriteLine(Test); new int F = C1.GetInt(out var Test); class C1 { public static int GetInt(out int v) { v = 1; return v; } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (5,9): error CS0116: A namespace cannot directly contain members such as fields or methods // new int F = C1.GetInt(out var Test); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "F").WithLocation(5, 9), // (5,9): warning CS0109: The member '<invalid-global-code>.F' does not hide an accessible member. The new keyword is not required. // new int F = C1.GetInt(out var Test); Diagnostic(ErrorCode.WRN_NewNotRequired, "F").WithArguments("<invalid-global-code>.F").WithLocation(5, 9) ); } [Fact] public void Scope_11() { var text = @" goto Test; Test: System.Console.WriteLine(); new void M() { goto Test; Test: System.Console.WriteLine(); }"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (5,10): error CS0116: A namespace cannot directly contain members such as fields or methods // new void M() Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "M").WithLocation(5, 10), // (5,10): warning CS0109: The member '<invalid-global-code>.M()' does not hide an accessible member. The new keyword is not required. // new void M() Diagnostic(ErrorCode.WRN_NewNotRequired, "M").WithArguments("<invalid-global-code>.M()").WithLocation(5, 10) ); } [Fact] public void Scope_12() { var text = @" using alias1 = Test; string Test() => ""1""; System.Console.WriteLine(Test()); class Test {} struct Derived { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; struct Derived { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 6 Test().ToString(); // 7 Test().EndsWith(null); // 8 var d = new System.Func<string>(Test); // 9 d(); _ = nameof(Test); // 10 } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 33), // (21,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(21, 20), // (36,38): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 6 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(36, 38), // (37,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 7 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(37, 13), // (38,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 8 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(38, 13), // (39,45): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // var d = new System.Func<string>(Test); // 9 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(39, 45), // (41,24): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 10 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(41, 24) ); } [Fact] public void Scope_13() { var text = @" using alias1 = Test; string Test() => ""1""; System.Console.WriteLine(Test()); class Test {} interface Derived { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; interface Derived { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 6 Test().ToString(); // 7 Test().EndsWith(null); // 8 var d = new System.Func<string>(Test); // 9 d(); _ = nameof(Test); // 10 } } } "; var comp = CreateCompilation(text, targetFramework: TargetFramework.NetCoreApp, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 33), // (21,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(21, 20), // (36,38): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 6 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(36, 38), // (37,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 7 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(37, 13), // (38,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 8 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(38, 13), // (39,45): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // var d = new System.Func<string>(Test); // 9 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(39, 45), // (41,24): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 10 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(41, 24) ); } [Fact] public void Scope_14() { var text = @" using alias1 = Test; string Test() => ""1""; System.Console.WriteLine(Test()); class Test {} delegate Test D(alias1 x); namespace N1 { using alias2 = Test; delegate Test D(alias2 x); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics(); } [Fact] public void Scope_15() { var text = @" const int Test = 1; System.Console.WriteLine(Test); class Test {} enum E1 { T = Test, } namespace N1 { enum E1 { T = Test, } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (9,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // T = Test, Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(9, 9), // (16,13): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // T = Test, Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 13) ); } [Fact] public void Scope_16() { var text1 = @" using alias1 = System.String; alias1 x = ""1""; alias2 y = ""1""; System.Console.WriteLine(x); System.Console.WriteLine(y); local(); "; var text2 = @" using alias2 = System.String; void local() { alias1 a = ""2""; alias2 b = ""2""; System.Console.WriteLine(a); System.Console.WriteLine(b); } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,1): error CS8802: Only one compilation unit can have top-level statements. // void local() Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "void").WithLocation(3, 1), // (3,6): warning CS8321: The local function 'local' is declared but never used // void local() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(3, 6), // (4,1): error CS0246: The type or namespace name 'alias2' could not be found (are you missing a using directive or an assembly reference?) // alias2 y = "1"; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias2").WithArguments("alias2").WithLocation(4, 1), // (5,5): error CS0246: The type or namespace name 'alias1' could not be found (are you missing a using directive or an assembly reference?) // alias1 a = "2"; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias1").WithArguments("alias1").WithLocation(5, 5), // (7,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(7, 1) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var nameRef = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "alias1" && !id.Parent.IsKind(SyntaxKind.NameEquals)).Single(); Assert.NotEmpty(model1.LookupNamespacesAndTypes(nameRef.SpanStart, name: "alias1")); Assert.Empty(model1.LookupNamespacesAndTypes(nameRef.SpanStart, name: "alias2")); nameRef = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "alias2").Single(); model1.GetDiagnostics(nameRef.Ancestors().OfType<StatementSyntax>().First().Span).Verify( // (4,1): error CS0246: The type or namespace name 'alias2' could not be found (are you missing a using directive or an assembly reference?) // alias2 y = "1"; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias2").WithArguments("alias2").WithLocation(4, 1) ); model1.GetDiagnostics().Verify( // (4,1): error CS0246: The type or namespace name 'alias2' could not be found (are you missing a using directive or an assembly reference?) // alias2 y = "1"; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias2").WithArguments("alias2").WithLocation(4, 1), // (7,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(7, 1) ); var tree2 = comp.SyntaxTrees[1]; var model2 = comp.GetSemanticModel(tree2); nameRef = tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "alias2" && !id.Parent.IsKind(SyntaxKind.NameEquals)).Single(); Assert.Empty(model2.LookupNamespacesAndTypes(nameRef.SpanStart, name: "alias1")); Assert.NotEmpty(model2.LookupNamespacesAndTypes(nameRef.SpanStart, name: "alias2")); nameRef = tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "alias1").Single(); model2.GetDiagnostics(nameRef.Ancestors().OfType<StatementSyntax>().First().Span).Verify( // (5,5): error CS0246: The type or namespace name 'alias1' could not be found (are you missing a using directive or an assembly reference?) // alias1 a = "2"; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias1").WithArguments("alias1").WithLocation(5, 5) ); model2.GetDiagnostics().Verify( // (3,1): error CS8802: Only one compilation unit can have top-level statements. // void local() Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "void").WithLocation(3, 1), // (3,6): warning CS8321: The local function 'local' is declared but never used // void local() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(3, 6), // (5,5): error CS0246: The type or namespace name 'alias1' could not be found (are you missing a using directive or an assembly reference?) // alias1 a = "2"; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias1").WithArguments("alias1").WithLocation(5, 5) ); } [Fact] public void Scope_17() { var text = @" using alias1 = N2.Test; using N2; string Test = ""1""; System.Console.WriteLine(Test); namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; using N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 20) ); } [Fact] public void Scope_18() { var text1 = @" string Test = ""1""; System.Console.WriteLine(Test); "; var text2 = @" using alias1 = N2.Test; using N2; namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; using N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 20) ); } [Fact] public void Scope_19() { var text = @" using alias1 = N2.Test; using N2; string Test() => ""1""; System.Console.WriteLine(Test()); namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; using N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 33), // (21,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(21, 20) ); } [Fact] public void Scope_20() { var text1 = @" string Test() => ""1""; System.Console.WriteLine(Test()); "; var text2 = @" using alias1 = N2.Test; using N2; namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; using N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 33), // (18,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 20) ); } [Fact] public void Scope_21() { var text = @" using Test = N2.Test; string Test = ""1""; System.Console.WriteLine(Test); namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; System.Console.WriteLine(x); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; using Test = N2.Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 20) ); } [Fact] public void Scope_22() { var text1 = @" string Test = ""1""; System.Console.WriteLine(Test); "; var text2 = @" using Test = N2.Test; namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; System.Console.WriteLine(x); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; using Test = N2.Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 20) ); } [Fact] public void Scope_23() { var text = @" using Test = N2.Test; string Test() => ""1""; System.Console.WriteLine(Test()); namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; System.Console.WriteLine(x); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; using Test = N2.Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 33), // (21,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(21, 20) ); } [Fact] public void Scope_24() { var text1 = @" string Test() => ""1""; System.Console.WriteLine(Test()); "; var text2 = @" using Test = N2.Test; namespace N2 { class Test {} } class Derived : Test { void M() { Test x = null; System.Console.WriteLine(x); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; using Test = N2.Test; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 33), // (18,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 20) ); } [Fact] public void Scope_25() { var text = @" using alias1 = N2.Test; using static N2; string Test = ""1""; System.Console.WriteLine(Test); class N2 { public class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; using static N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 20) ); } [Fact] public void Scope_26() { var text1 = @" string Test = ""1""; System.Console.WriteLine(Test); "; var text2 = @" using alias1 = N2.Test; using static N2; class N2 { public class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test); // 1 Test.ToString(); // 2 Test.EndsWith(null); // 3 _ = nameof(Test); // 4 } } namespace N1 { using alias2 = Test; using static N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test.EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 20) ); } [Fact] public void Scope_27() { var text = @" using alias1 = N2.Test; using static N2; string Test() => ""1""; System.Console.WriteLine(Test()); class N2 { public class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; using static N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (16,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 34), // (17,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(17, 9), // (18,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 9), // (19,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(19, 33), // (21,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(21, 20) ); } [Fact] public void Scope_28() { var text1 = @" string Test() => ""1""; System.Console.WriteLine(Test()); "; var text2 = @" using alias1 = N2.Test; using static N2; class N2 { public class Test {} } class Derived : Test { void M() { Test x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using alias2 = Test; using static N2; class Derived : Test { void M() { Test x = null; alias2 y = x; System.Console.WriteLine(y); _ = nameof(Test); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 33), // (18,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 20) ); } [Fact] public void Scope_29() { var text = @" using static N2; string Test() => ""1""; System.Console.WriteLine(Test()); class N2 { public static string Test() => null; } class Derived { void M() { System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using static N2; class Derived { void M() { System.Console.WriteLine(Test()); Test().ToString(); Test().EndsWith(null); var d = new System.Func<string>(Test); d(); _ = nameof(Test); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): hidden CS8019: Unnecessary using directive. // using static N2; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static N2;").WithLocation(2, 1), // (13,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 34), // (14,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(14, 9), // (15,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 9), // (16,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(16, 33), // (18,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(18, 20) ); } [Fact] public void Scope_30() { var text1 = @" string Test() => ""1""; System.Console.WriteLine(Test()); "; var text2 = @" using static N2; class N2 { public static string Test() => null; } class Derived { void M() { System.Console.WriteLine(Test()); // 1 Test().ToString(); // 2 Test().EndsWith(null); // 3 System.Func<string> d = Test; // 4 d(); _ = nameof(Test); // 5 } } namespace N1 { using static N2; class Derived { void M() { System.Console.WriteLine(Test()); Test().ToString(); Test().EndsWith(null); var d = new System.Func<string>(Test); d(); _ = nameof(Test); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): hidden CS8019: Unnecessary using directive. // using static N2; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using static N2;").WithLocation(2, 1), // (10,34): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Console.WriteLine(Test()); // 1 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(10, 34), // (11,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().ToString(); // 2 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(11, 9), // (12,9): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // Test().EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(12, 9), // (13,33): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // System.Func<string> d = Test; // 4 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(13, 33), // (15,20): error CS8801: Cannot use local variable or local function 'Test' declared in a top-level statement in this context. // _ = nameof(Test); // 5 Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "Test").WithArguments("Test").WithLocation(15, 20) ); } [Fact] public void Scope_31() { var text = @" using alias1 = args; System.Console.WriteLine(args); class args {} class Derived : args { void M() { args x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(args); // 1 args.ToString(); // 2 args[0].EndsWith(null); // 3 _ = nameof(args); } } namespace N1 { using alias2 = args; class Derived : args { void M() { args x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(args); // 4 args.ToString(); // 5 args[0].EndsWith(null); // 6 _ = nameof(args); } } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (15,34): error CS0119: 'args' is a type, which is not valid in the given context // System.Console.WriteLine(args); // 1 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(15, 34), // (16,9): error CS0120: An object reference is required for the non-static field, method, or property 'object.ToString()' // args.ToString(); // 2 Diagnostic(ErrorCode.ERR_ObjectRequired, "args.ToString").WithArguments("object.ToString()").WithLocation(16, 9), // (17,9): error CS0119: 'args' is a type, which is not valid in the given context // args[0].EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(17, 9), // (33,38): error CS0119: 'args' is a type, which is not valid in the given context // System.Console.WriteLine(args); // 4 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(33, 38), // (34,13): error CS0120: An object reference is required for the non-static field, method, or property 'object.ToString()' // args.ToString(); // 5 Diagnostic(ErrorCode.ERR_ObjectRequired, "args.ToString").WithArguments("object.ToString()").WithLocation(34, 13), // (35,13): error CS0119: 'args' is a type, which is not valid in the given context // args[0].EndsWith(null); // 6 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(35, 13) ); var testType = ((Compilation)comp).GetTypeByMetadataName("args"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var nameRefs = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "args").ToArray(); var nameRef = nameRefs[0]; Assert.Equal("using alias1 = args;", nameRef.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); var names = model.LookupNames(nameRef.SpanStart); Assert.Contains("args", names); var symbols = model.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.False(symbols.Any(s => s.Kind == SymbolKind.Parameter)); Assert.Same(testType, model.LookupSymbols(nameRef.SpanStart, name: "args").Single()); nameRef = nameRefs[1]; Assert.Equal("System.Console.WriteLine(args)", nameRef.Parent.Parent.Parent.ToString()); var parameter = model.GetSymbolInfo(nameRef).Symbol; Assert.Equal("System.String[] args", parameter.ToTestDisplayString()); Assert.Equal("<top-level-statements-entry-point>", parameter.ContainingSymbol.ToTestDisplayString()); names = model.LookupNames(nameRef.SpanStart); Assert.Contains("args", names); symbols = model.LookupSymbols(nameRef.SpanStart); Assert.DoesNotContain(testType, symbols); Assert.Contains(parameter, symbols); Assert.Same(parameter, model.LookupSymbols(nameRef.SpanStart, name: "args").Single()); symbols = model.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(parameter, symbols); Assert.Same(testType, model.LookupNamespacesAndTypes(nameRef.SpanStart, name: "args").Single()); nameRef = nameRefs[2]; Assert.Equal(": args", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(parameter, model, nameRef); nameRef = nameRefs[4]; Assert.Equal("System.Console.WriteLine(args)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(parameter, model, nameRef); nameRef = nameRefs[8]; Assert.Equal("using alias2 = args;", nameRef.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(parameter, model, nameRef); nameRef = nameRefs[9]; Assert.Equal(": args", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(parameter, model, nameRef); nameRef = nameRefs[11]; Assert.Equal("System.Console.WriteLine(args)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(parameter, model, nameRef); void verifyModel(ISymbol declSymbol, SemanticModel model, IdentifierNameSyntax nameRef) { var names = model.LookupNames(nameRef.SpanStart); Assert.Contains("args", names); var symbols = model.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model.LookupSymbols(nameRef.SpanStart, name: "args").Single()); symbols = model.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.DoesNotContain(declSymbol, symbols); Assert.Same(testType, model.LookupNamespacesAndTypes(nameRef.SpanStart, name: "args").Single()); } } [Fact] public void Scope_32() { var text1 = @" System.Console.WriteLine(args); "; var text2 = @" using alias1 = args; class args {} class Derived : args { void M() { args x = null; alias1 y = x; System.Console.WriteLine(y); System.Console.WriteLine(args); // 1 args.ToString(); // 2 args[0].EndsWith(null); // 3 _ = nameof(args); } } namespace N1 { using alias2 = args; class Derived : args { void M() { args x = null; alias2 y = x; System.Console.WriteLine(y); System.Console.WriteLine(args); // 4 args.ToString(); // 5 args[0].EndsWith(null); // 6 _ = nameof(args); } } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,34): error CS0119: 'args' is a type, which is not valid in the given context // System.Console.WriteLine(args); // 1 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(13, 34), // (14,9): error CS0120: An object reference is required for the non-static field, method, or property 'object.ToString()' // args.ToString(); // 2 Diagnostic(ErrorCode.ERR_ObjectRequired, "args.ToString").WithArguments("object.ToString()").WithLocation(14, 9), // (15,9): error CS0119: 'args' is a type, which is not valid in the given context // args[0].EndsWith(null); // 3 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(15, 9), // (31,38): error CS0119: 'args' is a type, which is not valid in the given context // System.Console.WriteLine(args); // 4 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(31, 38), // (32,13): error CS0120: An object reference is required for the non-static field, method, or property 'object.ToString()' // args.ToString(); // 5 Diagnostic(ErrorCode.ERR_ObjectRequired, "args.ToString").WithArguments("object.ToString()").WithLocation(32, 13), // (33,13): error CS0119: 'args' is a type, which is not valid in the given context // args[0].EndsWith(null); // 6 Diagnostic(ErrorCode.ERR_BadSKunknown, "args").WithArguments("args", "type").WithLocation(33, 13) ); var testType = ((Compilation)comp).GetTypeByMetadataName("args"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree = comp.SyntaxTrees[1]; var model = comp.GetSemanticModel(tree); var nameRefs = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "args").ToArray(); var nameRef = nameRefs[0]; Assert.Equal("using alias1 = args;", nameRef.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); var names = model.LookupNames(nameRef.SpanStart); Assert.Contains("args", names); var symbols = model.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.False(symbols.Any(s => s.Kind == SymbolKind.Parameter)); Assert.Same(testType, model.LookupSymbols(nameRef.SpanStart, name: "args").Single()); nameRef = nameRefs[1]; Assert.Equal(": args", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(model, nameRef); nameRef = nameRefs[3]; Assert.Equal("System.Console.WriteLine(args)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(model, nameRef); nameRef = nameRefs[7]; Assert.Equal("using alias2 = args;", nameRef.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(model, nameRef); nameRef = nameRefs[8]; Assert.Equal(": args", nameRef.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(model, nameRef); nameRef = nameRefs[10]; Assert.Equal("System.Console.WriteLine(args)", nameRef.Parent.Parent.Parent.ToString()); Assert.Same(testType, model.GetSymbolInfo(nameRef).Symbol); verifyModel(model, nameRef); void verifyModel(SemanticModel model, IdentifierNameSyntax nameRef) { var names = model.LookupNames(nameRef.SpanStart); Assert.Contains("args", names); var symbols = model.LookupSymbols(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.False(symbols.Any(s => s.Kind == SymbolKind.Parameter)); Assert.Same(testType, model.LookupSymbols(nameRef.SpanStart, name: "args").Single()); symbols = model.LookupNamespacesAndTypes(nameRef.SpanStart); Assert.Contains(testType, symbols); Assert.False(symbols.Any(s => s.Kind == SymbolKind.Parameter)); Assert.Same(testType, model.LookupNamespacesAndTypes(nameRef.SpanStart, name: "args").Single()); } } [Fact] public void Scope_33() { var text = @" System.Console.WriteLine(args); class Test { void M() { System.Console.WriteLine(args); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (8,34): error CS0103: The name 'args' does not exist in the current context // System.Console.WriteLine(args); Diagnostic(ErrorCode.ERR_NameNotInContext, "args").WithArguments("args").WithLocation(8, 34) ); } [Fact] public void Scope_34() { var text1 = @" System.Console.WriteLine(args); "; var text2 = @" class Test { void M() { System.Console.WriteLine(args); } } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,34): error CS0103: The name 'args' does not exist in the current context // System.Console.WriteLine(args); Diagnostic(ErrorCode.ERR_NameNotInContext, "args").WithArguments("args").WithLocation(6, 34) ); } [Fact] public void LocalFunctionStatement_01() { var text = @" local(); void local() { System.Console.WriteLine(15); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "15"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single(); var reference = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "local").Single(); var local = model.GetDeclaredSymbol(declarator); Assert.Same(local, model.GetSymbolInfo(reference).Symbol); Assert.Equal("void local()", local.ToTestDisplayString()); Assert.Equal(MethodKind.LocalFunction, ((IMethodSymbol)local).MethodKind); Assert.Equal(SymbolKind.Method, local.ContainingSymbol.Kind); Assert.False(local.ContainingSymbol.IsImplicitlyDeclared); Assert.Equal(SymbolKind.NamedType, local.ContainingSymbol.ContainingSymbol.Kind); Assert.False(local.ContainingSymbol.ContainingSymbol.IsImplicitlyDeclared); Assert.True(((INamespaceSymbol)local.ContainingSymbol.ContainingSymbol.ContainingSymbol).IsGlobalNamespace); VerifyFlowGraph(comp, tree.GetRoot(), @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Methods: [void local()] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'local();') Expression: IInvocationOperation (void local()) (OperationKind.Invocation, Type: System.Void) (Syntax: 'local()') Instance Receiver: null Arguments(0) Next (Regular) Block[B2] Leaving: {R1} { void local() Block[B0#0R1] - Entry Statements (0) Next (Regular) Block[B1#0R1] Block[B1#0R1] - Block Predecessors: [B0#0R1] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'System.Cons ... teLine(15);') Expression: IInvocationOperation (void System.Console.WriteLine(System.Int32 value)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'System.Cons ... iteLine(15)') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: value) (OperationKind.Argument, Type: null) (Syntax: '15') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 15) (Syntax: '15') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B2#0R1] Block[B2#0R1] - Exit Predecessors: [B1#0R1] Statements (0) } } Block[B2] - Exit Predecessors: [B1] Statements (0) "); } [Fact] public void LocalFunctionStatement_02() { var text = @" local(); void local() => System.Console.WriteLine(""Hi!""); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void LocalFunctionStatement_03() { var text = @" local(); void I1.local() { System.Console.WriteLine(""Hi!""); } interface I1 { void local(); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS0103: The name 'local' does not exist in the current context // local(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(2, 1), // (4,6): error CS0540: '<invalid-global-code>.I1.local()': containing type does not implement interface 'I1' // void I1.local() Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1").WithArguments("<invalid-global-code>.I1.local()", "I1").WithLocation(4, 6), // (4,9): error CS0116: A namespace cannot directly contain members such as fields or methods // void I1.local() Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "local").WithLocation(4, 9) ); } [Fact] public void LocalFunctionStatement_04() { var text = @" new void localA() => System.Console.WriteLine(); localA(); public void localB() => System.Console.WriteLine(); localB(); virtual void localC() => System.Console.WriteLine(); localC(); sealed void localD() => System.Console.WriteLine(); localD(); override void localE() => System.Console.WriteLine(); localE(); abstract void localF() => System.Console.WriteLine(); localF(); partial void localG() => System.Console.WriteLine(); localG(); extern void localH() => System.Console.WriteLine(); localH(); [System.Obsolete()] void localI() => System.Console.WriteLine(); localI(); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,10): error CS0116: A namespace cannot directly contain members such as fields or methods // new void localA() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "localA").WithLocation(2, 10), // (2,10): warning CS0109: The member '<invalid-global-code>.localA()' does not hide an accessible member. The new keyword is not required. // new void localA() => System.Console.WriteLine(); Diagnostic(ErrorCode.WRN_NewNotRequired, "localA").WithArguments("<invalid-global-code>.localA()").WithLocation(2, 10), // (3,1): error CS0103: The name 'localA' does not exist in the current context // localA(); Diagnostic(ErrorCode.ERR_NameNotInContext, "localA").WithArguments("localA").WithLocation(3, 1), // (4,1): error CS0106: The modifier 'public' is not valid for this item // public void localB() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "public").WithArguments("public").WithLocation(4, 1), // (6,14): error CS0116: A namespace cannot directly contain members such as fields or methods // virtual void localC() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "localC").WithLocation(6, 14), // (6,14): error CS0621: '<invalid-global-code>.localC()': virtual or abstract members cannot be private // virtual void localC() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_VirtualPrivate, "localC").WithArguments("<invalid-global-code>.localC()").WithLocation(6, 14), // (7,1): error CS0103: The name 'localC' does not exist in the current context // localC(); Diagnostic(ErrorCode.ERR_NameNotInContext, "localC").WithArguments("localC").WithLocation(7, 1), // (8,13): error CS0116: A namespace cannot directly contain members such as fields or methods // sealed void localD() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "localD").WithLocation(8, 13), // (8,13): error CS0238: '<invalid-global-code>.localD()' cannot be sealed because it is not an override // sealed void localD() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_SealedNonOverride, "localD").WithArguments("<invalid-global-code>.localD()").WithLocation(8, 13), // (9,1): error CS0103: The name 'localD' does not exist in the current context // localD(); Diagnostic(ErrorCode.ERR_NameNotInContext, "localD").WithArguments("localD").WithLocation(9, 1), // (10,15): error CS0116: A namespace cannot directly contain members such as fields or methods // override void localE() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "localE").WithLocation(10, 15), // (10,15): error CS0621: '<invalid-global-code>.localE()': virtual or abstract members cannot be private // override void localE() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_VirtualPrivate, "localE").WithArguments("<invalid-global-code>.localE()").WithLocation(10, 15), // (10,15): error CS0115: '<invalid-global-code>.localE()': no suitable method found to override // override void localE() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_OverrideNotExpected, "localE").WithArguments("<invalid-global-code>.localE()").WithLocation(10, 15), // (11,1): error CS0103: The name 'localE' does not exist in the current context // localE(); Diagnostic(ErrorCode.ERR_NameNotInContext, "localE").WithArguments("localE").WithLocation(11, 1), // (12,15): error CS0116: A namespace cannot directly contain members such as fields or methods // abstract void localF() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "localF").WithLocation(12, 15), // (12,15): error CS0500: '<invalid-global-code>.localF()' cannot declare a body because it is marked abstract // abstract void localF() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_AbstractHasBody, "localF").WithArguments("<invalid-global-code>.localF()").WithLocation(12, 15), // (12,15): error CS0621: '<invalid-global-code>.localF()': virtual or abstract members cannot be private // abstract void localF() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_VirtualPrivate, "localF").WithArguments("<invalid-global-code>.localF()").WithLocation(12, 15), // (13,1): error CS0103: The name 'localF' does not exist in the current context // localF(); Diagnostic(ErrorCode.ERR_NameNotInContext, "localF").WithArguments("localF").WithLocation(13, 1), // (14,14): error CS0116: A namespace cannot directly contain members such as fields or methods // partial void localG() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "localG").WithLocation(14, 14), // (14,14): error CS0759: No defining declaration found for implementing declaration of partial method '<invalid-global-code>.localG()' // partial void localG() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "localG").WithArguments("<invalid-global-code>.localG()").WithLocation(14, 14), // (14,14): error CS0751: A partial method must be declared within a partial type // partial void localG() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_PartialMethodOnlyInPartialClass, "localG").WithLocation(14, 14), // (15,1): error CS0103: The name 'localG' does not exist in the current context // localG(); Diagnostic(ErrorCode.ERR_NameNotInContext, "localG").WithArguments("localG").WithLocation(15, 1), // (16,13): error CS0179: 'localH()' cannot be extern and declare a body // extern void localH() => System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_ExternHasBody, "localH").WithArguments("localH()").WithLocation(16, 13), // (20,1): warning CS0612: 'localI()' is obsolete // localI(); Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "localI()").WithArguments("localI()").WithLocation(20, 1) ); } [Fact] public void LocalFunctionStatement_05() { var text = @" void local1() => System.Console.Write(""1""); local1(); void local2() => System.Console.Write(""2""); local2(); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "12"); } [Fact] public void LocalFunctionStatement_06() { var text = @" local(); static void local() { System.Console.WriteLine(""Hi!""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void LocalFunctionStatement_07() { var text1 = @" local1(1); void local1(int x) {} local2(); "; var text2 = @" void local1(byte y) {} void local2() { local1(2); } "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // void local1(byte y) Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "void").WithLocation(2, 1), // (5,1): error CS0103: The name 'local2' does not exist in the current context // local2(); Diagnostic(ErrorCode.ERR_NameNotInContext, "local2").WithArguments("local2").WithLocation(5, 1), // (5,6): warning CS8321: The local function 'local2' is declared but never used // void local2() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local2").WithArguments("local2").WithLocation(5, 6) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var symbol1 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single()); Assert.Equal("void local1(System.Int32 x)", symbol1.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "local1").Single()).Symbol); var tree2 = comp.SyntaxTrees[1]; var model2 = comp.GetSemanticModel(tree2); var symbol2 = model2.GetDeclaredSymbol(tree2.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().First()); Assert.Equal("void local1(System.Byte y)", symbol2.ToTestDisplayString()); Assert.Same(symbol2, model2.GetSymbolInfo(tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "local1").Single()).Symbol); } [Fact] public void LocalFunctionStatement_08() { var text = @" void local() { System.Console.WriteLine(""Hi!""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,6): warning CS8321: The local function 'local' is declared but never used // void local() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(2, 6) ); CompileAndVerify(comp, expectedOutput: ""); } [Fact] public void LocalFunctionStatement_09() { var text1 = @" local1(1); void local1(int x) {} local2(); void local1(byte y) {} void local2() { local1(2); } "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (7,6): error CS0128: A local variable or function named 'local1' is already defined in this scope // void local1(byte y) Diagnostic(ErrorCode.ERR_LocalDuplicate, "local1").WithArguments("local1").WithLocation(7, 6), // (7,6): warning CS8321: The local function 'local1' is declared but never used // void local1(byte y) Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local1").WithArguments("local1").WithLocation(7, 6) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var symbol1 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().First()); Assert.Equal("void local1(System.Int32 x)", symbol1.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "local1").First()).Symbol); var symbol2 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Skip(1).First()); Assert.Equal("void local1(System.Byte y)", symbol2.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "local1").Skip(1).Single()).Symbol); } [Fact] public void LocalFunctionStatement_10() { var text = @" int i = 1; local(); System.Console.WriteLine(i); void local() { i++; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "2"); } [Fact] public void LocalFunctionStatement_11() { var text1 = @" args(1); void args(int x) {} "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,6): error CS0136: A local or parameter named 'args' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter // void args(int x) Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "args").WithArguments("args").WithLocation(3, 6) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var symbol1 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().First()); Assert.Equal("void args(System.Int32 x)", symbol1.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "args").Single()).Symbol); } [Fact] public void LocalFunctionStatement_12() { var text1 = @" local(1); void local<args>(args x) { System.Console.WriteLine(x); } "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "1"); } [Fact] public void LocalFunctionStatement_13() { var text1 = @" local(); void local() { var args = 2; System.Console.WriteLine(args); } "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "2"); } [Fact] public void LocalFunctionStatement_14() { var text1 = @" local(3); void local(int args) { System.Console.WriteLine(args); } "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "3"); } [Fact] public void LocalFunctionStatement_15() { var text1 = @" local(); void local() { args(4); void args(int x) { System.Console.WriteLine(x); } } "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "4"); } [Fact] public void LocalFunctionStatement_16() { var text1 = @" using System.Linq; _ = from local in new object[0] select local; local(); void local() {} "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,10): error CS1931: The range variable 'local' conflicts with a previous declaration of 'local' // _ = from local in new object[0] select local; Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "local").WithArguments("local").WithLocation(3, 10) ); } [Fact] public void LocalFunctionStatement_17() { var text = @" System.Console.WriteLine(); string await() => ""Hi!""; System.Console.WriteLine(await()); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,8): error CS4003: 'await' cannot be used as an identifier within an async method or lambda expression // string await() => "Hi!"; Diagnostic(ErrorCode.ERR_BadAwaitAsIdentifier, "await").WithLocation(3, 8), // (3,8): warning CS8321: The local function 'await' is declared but never used // string await() => "Hi!"; Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "await").WithArguments("await").WithLocation(3, 8), // (4,32): error CS1525: Invalid expression term ')' // System.Console.WriteLine(await()); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(4, 32) ); } [Fact] public void LocalFunctionStatement_18() { var text = @" string async() => ""Hi!""; System.Console.WriteLine(async()); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void Lambda_01() { var text = @" int i = 1; System.Action l = () => i++; l(); System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "2"); } [Fact] public void PropertyDeclaration_01() { var text = @" _ = local; int local => 1; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,5): error CS0103: The name 'local' does not exist in the current context // _ = local; Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(2, 5), // (4,5): error CS0116: A namespace cannot directly contain members such as fields or methods // int local => 1; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "local").WithLocation(4, 5) ); } [Fact] public void PropertyDeclaration_02() { var text = @" _ = local; int local { get => 1; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,5): error CS0103: The name 'local' does not exist in the current context // _ = local; Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(2, 5), // (4,5): error CS0116: A namespace cannot directly contain members such as fields or methods // int local { get => 1; } Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "local").WithLocation(4, 5) ); } [Fact] public void PropertyDeclaration_03() { var text = @" _ = local; int local { get { return 1; } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,5): error CS0103: The name 'local' does not exist in the current context // _ = local; Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(2, 5), // (4,5): error CS0116: A namespace cannot directly contain members such as fields or methods // int local { get { return 1; } } Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "local").WithLocation(4, 5) ); } [Fact] public void EventDeclaration_01() { var text = @" local += null; event System.Action local; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS0103: The name 'local' does not exist in the current context // local += null; Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(2, 1), // (4,21): error CS0116: A namespace cannot directly contain members such as fields or methods // event System.Action local; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "local").WithLocation(4, 21) ); } [Fact] public void EventDeclaration_02() { var text = @" local -= null; event System.Action local { add {} remove {} } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS0103: The name 'local' does not exist in the current context // local -= null; Diagnostic(ErrorCode.ERR_NameNotInContext, "local").WithArguments("local").WithLocation(2, 1), // (4,21): error CS0116: A namespace cannot directly contain members such as fields or methods // event System.Action local Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "local").WithLocation(4, 21) ); } [Fact] public void LabeledStatement_01() { var text = @" goto label1; label1: System.Console.WriteLine(""Hi!""); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<LabeledStatementSyntax>().Single(); var reference = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "label1").Single(); var label = model.GetDeclaredSymbol(declarator); Assert.Same(label, model.GetSymbolInfo(reference).Symbol); Assert.Equal("label1", label.ToTestDisplayString()); Assert.Equal(SymbolKind.Label, label.Kind); Assert.Equal(SymbolKind.Method, label.ContainingSymbol.Kind); Assert.False(label.ContainingSymbol.IsImplicitlyDeclared); Assert.Equal(SymbolKind.NamedType, label.ContainingSymbol.ContainingSymbol.Kind); Assert.False(label.ContainingSymbol.ContainingSymbol.IsImplicitlyDeclared); Assert.True(((INamespaceSymbol)label.ContainingSymbol.ContainingSymbol.ContainingSymbol).IsGlobalNamespace); } [Fact] public void LabeledStatement_02() { var text = @" goto label1; label1: System.Console.WriteLine(""Hi!""); label1: System.Console.WriteLine(); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,1): error CS0140: The label 'label1' is a duplicate // label1: System.Console.WriteLine(); Diagnostic(ErrorCode.ERR_DuplicateLabel, "label1").WithArguments("label1").WithLocation(4, 1) ); } [Fact] public void LabeledStatement_03() { var text1 = @" goto label1; label1: System.Console.Write(1); "; var text2 = @" label1: System.Console.Write(2); goto label1; "; var comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS8802: Only one compilation unit can have top-level statements. // label1: System.Console.Write(2); Diagnostic(ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, "label1").WithLocation(2, 1) ); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var symbol1 = model1.GetDeclaredSymbol(tree1.GetRoot().DescendantNodes().OfType<LabeledStatementSyntax>().Single()); Assert.Equal("label1", symbol1.ToTestDisplayString()); Assert.Same(symbol1, model1.GetSymbolInfo(tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "label1").Single()).Symbol); var tree2 = comp.SyntaxTrees[1]; var model2 = comp.GetSemanticModel(tree2); var symbol2 = model2.GetDeclaredSymbol(tree2.GetRoot().DescendantNodes().OfType<LabeledStatementSyntax>().Single()); Assert.Equal("label1", symbol2.ToTestDisplayString()); Assert.NotEqual(symbol1, symbol2); Assert.Same(symbol2, model2.GetSymbolInfo(tree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "label1").Single()).Symbol); } [Fact] public void LabeledStatement_04() { var text = @" goto args; args: System.Console.WriteLine(""Hi!""); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); Assert.False(IsNullableAnalysisEnabled(comp)); // To make sure we test incremental binding for SemanticModel var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<LabeledStatementSyntax>().Single(); var reference = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "args").Single(); var label = model.GetDeclaredSymbol(declarator); Assert.Same(label, model.GetSymbolInfo(reference).Symbol); Assert.Equal("args", label.ToTestDisplayString()); Assert.Equal(SymbolKind.Label, label.Kind); Assert.Equal(SymbolKind.Method, label.ContainingSymbol.Kind); Assert.False(label.ContainingSymbol.IsImplicitlyDeclared); Assert.Equal(SymbolKind.NamedType, label.ContainingSymbol.ContainingSymbol.Kind); Assert.False(label.ContainingSymbol.ContainingSymbol.IsImplicitlyDeclared); Assert.True(((INamespaceSymbol)label.ContainingSymbol.ContainingSymbol.ContainingSymbol).IsGlobalNamespace); } [Fact] public void ExplicitMain_01() { var text = @" static void Main() {} System.Console.Write(""Hi!""); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,13): warning CS7022: The entry point of the program is global code; ignoring 'Main()' entry point. // static void Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main()").WithLocation(2, 13), // (2,13): warning CS8321: The local function 'Main' is declared but never used // static void Main() Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Main").WithArguments("Main").WithLocation(2, 13) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_02() { var text = @" System.Console.Write(""H""); Main(); System.Console.Write(""!""); static void Main() { System.Console.Write(""i""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,13): warning CS7022: The entry point of the program is global code; ignoring 'Main()' entry point. // static void Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main()").WithLocation(6, 13) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_03() { var text = @" using System; using System.Threading.Tasks; System.Console.Write(""Hi!""); class Program { static async Task Main() { Console.Write(""hello ""); await Task.Factory.StartNew(() => 5); Console.Write(""async main""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (9,23): warning CS7022: The entry point of the program is global code; ignoring 'Program.Main()' entry point. // static async Task Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program.Main()").WithLocation(9, 23) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_04() { var text = @" using System; using System.Threading.Tasks; await Task.Factory.StartNew(() => 5); System.Console.Write(""Hi!""); class Program { static async Task Main() { Console.Write(""hello ""); await Task.Factory.StartNew(() => 5); Console.Write(""async main""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (10,23): warning CS7022: The entry point of the program is global code; ignoring 'Program.Main()' entry point. // static async Task Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program.Main()").WithLocation(10, 23) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_05() { var text = @" using System; using System.Threading.Tasks; await Task.Factory.StartNew(() => 5); System.Console.Write(""Hi!""); class Program { static void Main() { Console.Write(""hello ""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (10,17): warning CS7022: The entry point of the program is global code; ignoring 'Program.Main()' entry point. // static void Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program.Main()").WithLocation(10, 17) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_06() { var text = @" System.Console.Write(""Hi!""); class Program { static void Main() { System.Console.Write(""hello ""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,17): warning CS7022: The entry point of the program is global code; ignoring 'Program.Main()' entry point. // static void Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program.Main()").WithLocation(6, 17) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_07() { var text = @" using System; using System.Threading.Tasks; System.Console.Write(""Hi!""); class Program { static void Main(string[] args) { Console.Write(""hello ""); } static async Task Main() { Console.Write(""hello ""); await Task.Factory.StartNew(() => 5); Console.Write(""async main""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (9,17): warning CS7022: The entry point of the program is global code; ignoring 'Program.Main(string[])' entry point. // static void Main(string[] args) Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program.Main(string[])").WithLocation(9, 17), // (14,23): warning CS7022: The entry point of the program is global code; ignoring 'Program.Main()' entry point. // static async Task Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program.Main()").WithLocation(14, 23) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_08() { var text = @" using System; using System.Threading.Tasks; await Task.Factory.StartNew(() => 5); System.Console.Write(""Hi!""); class Program { static void Main() { Console.Write(""hello ""); } static async Task Main(string[] args) { await Task.Factory.StartNew(() => 5); Console.Write(""async main""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (10,17): warning CS7022: The entry point of the program is global code; ignoring 'Program.Main()' entry point. // static void Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program.Main()").WithLocation(10, 17), // (15,23): warning CS7022: The entry point of the program is global code; ignoring 'Program.Main(string[])' entry point. // static async Task Main(string[] args) Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program.Main(string[])").WithLocation(15, 23) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_09() { var text1 = @" using System; using System.Threading.Tasks; string s = ""Hello world!""; foreach (var c in s) { await N1.Helpers.Wait(); Console.Write(c); } Console.WriteLine(); namespace N1 { class Helpers { static void Main() { } public static async Task Wait() { await Task.Delay(500); } } }"; var text4 = @" using System.Threading.Tasks; class Helpers { public static async Task Wait() { await Task.Delay(500); } } "; var comp = CreateCompilation(new[] { text1, text4 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // (19,21): warning CS7022: The entry point of the program is global code; ignoring 'Helpers.Main()' entry point. // static void Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("N1.Helpers.Main()").WithLocation(19, 21) ); } [Fact] public void ExplicitMain_10() { var text = @" using System.Threading.Tasks; System.Console.Write(""Hi!""); class Program { static void Main() { } static async Task Main(string[] args) { await Task.Factory.StartNew(() => 5); } } class Program2 { static void Main(string[] args) { } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe.WithMainTypeName("Program"), parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // error CS8804: Cannot specify /main if there is a compilation unit with top-level statements. Diagnostic(ErrorCode.ERR_SimpleProgramDisallowsMainType).WithLocation(1, 1), // (12,23): warning CS8892: Method 'Program.Main(string[])' will not be used as an entry point because a synchronous entry point 'Program.Main()' was found. // static async Task Main(string[] args) Diagnostic(ErrorCode.WRN_SyncAndAsyncEntryPoints, "Main").WithArguments("Program.Main(string[])", "Program.Main()").WithLocation(12, 23) ); } [Fact] public void ExplicitMain_11() { var text = @" using System.Threading.Tasks; System.Console.Write(""Hi!""); class Program { static void Main() { } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe.WithMainTypeName(""), parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // error CS7088: Invalid 'MainTypeName' value: ''. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("MainTypeName", "").WithLocation(1, 1), // error CS8804: Cannot specify /main if there is a compilation unit with top-level statements. Diagnostic(ErrorCode.ERR_SimpleProgramDisallowsMainType).WithLocation(1, 1) ); } [Fact] public void ExplicitMain_12() { var text = @" System.Console.Write(""H""); Main(); System.Console.Write(""!""); void Main() { System.Console.Write(""i""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_13() { var text = @" System.Console.Write(""H""); Main(""""); System.Console.Write(""!""); static void Main(string args) { System.Console.Write(""i""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_14() { var text = @" System.Console.Write(""H""); Main(); System.Console.Write(""!""); static long Main() { System.Console.Write(""i""); return 0; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_15() { var text = @" System.Console.Write(""H""); Main(); System.Console.Write(""!""); static int Main() { System.Console.Write(""i""); return 0; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,12): warning CS7022: The entry point of the program is global code; ignoring 'Main()' entry point. // static int Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main()").WithLocation(6, 12) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_16() { var text = @" System.Console.Write(""H""); Main(null); System.Console.Write(""!""); static void Main(string[] args) { System.Console.Write(""i""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,13): warning CS7022: The entry point of the program is global code; ignoring 'Main(string[])' entry point. // static void Main(string[] args) Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main(string[])").WithLocation(6, 13) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_17() { var text = @" System.Console.Write(""H""); Main(null); System.Console.Write(""!""); static int Main(string[] args) { System.Console.Write(""i""); return 0; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,12): warning CS7022: The entry point of the program is global code; ignoring 'Main(string[])' entry point. // static int Main(string[] args) Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main(string[])").WithLocation(6, 12) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_18() { var text = @" using System.Threading.Tasks; System.Console.Write(""H""); await Main(); System.Console.Write(""!""); async static Task Main() { System.Console.Write(""i""); await Task.Yield(); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (8,19): warning CS7022: The entry point of the program is global code; ignoring 'Main()' entry point. // async static Task Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main()").WithLocation(8, 19) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_19() { var text = @" using System.Threading.Tasks; System.Console.Write(""H""); await Main(); System.Console.Write(""!""); static async Task<int> Main() { System.Console.Write(""i""); await Task.Yield(); return 0; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (8,24): warning CS7022: The entry point of the program is global code; ignoring 'Main()' entry point. // static async Task<int> Main() Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main()").WithLocation(8, 24) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_20() { var text = @" using System.Threading.Tasks; System.Console.Write(""H""); await Main(null); System.Console.Write(""!""); static async Task Main(string[] args) { System.Console.Write(""i""); await Task.Yield(); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (8,19): warning CS7022: The entry point of the program is global code; ignoring 'Main(string[])' entry point. // static async Task Main(string[] args) Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main(string[])").WithLocation(8, 19) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_21() { var text = @" using System.Threading.Tasks; System.Console.Write(""H""); await Main(null); System.Console.Write(""!""); static async Task<int> Main(string[] args) { System.Console.Write(""i""); await Task.Yield(); return 0; } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (8,24): warning CS7022: The entry point of the program is global code; ignoring 'Main(string[])' entry point. // static async Task<int> Main(string[] args) Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Main(string[])").WithLocation(8, 24) ); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_22() { var text = @" System.Console.Write(""H""); Main<int>(); System.Console.Write(""!""); static void Main<T>() { System.Console.Write(""i""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void ExplicitMain_23() { var text = @" System.Console.Write(""H""); local(); System.Console.Write(""!""); static void local() { Main(); static void Main() { System.Console.Write(""i""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void Yield_01() { var text = @"yield break;"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS1624: The body of '<top-level-statements-entry-point>' cannot be an iterator block because 'void' is not an iterator interface type // yield break; Diagnostic(ErrorCode.ERR_BadIteratorReturn, "yield break;").WithArguments("<top-level-statements-entry-point>", "void").WithLocation(1, 1) ); } [Fact] public void Yield_02() { var text = @"{yield return 0;}"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS1624: The body of '<top-level-statements-entry-point>' cannot be an iterator block because 'void' is not an iterator interface type // {yield return 0;} Diagnostic(ErrorCode.ERR_BadIteratorReturn, "{yield return 0;}").WithArguments("<top-level-statements-entry-point>", "void").WithLocation(1, 1) ); } [Fact] public void OutOfOrder_01() { var text = @" class C {} System.Console.WriteLine(1); System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(4, 1) ); } [Fact] public void OutOfOrder_02() { var text = @" System.Console.WriteLine(0); namespace C {} System.Console.WriteLine(1); System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(6, 1) ); } [Fact] public void OutOfOrder_03() { var text = @" class C {} System.Console.WriteLine(1); System.Console.WriteLine(2); class D {} System.Console.WriteLine(3); System.Console.WriteLine(4); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(4, 1) ); } [Fact] public void OutOfOrder_04() { var text = @" System.Console.WriteLine(0); namespace C {} System.Console.WriteLine(1); System.Console.WriteLine(2); namespace D {} System.Console.WriteLine(3); System.Console.WriteLine(4); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(6, 1) ); } [Fact] public void OutOfOrder_05() { var text = @" System.Console.WriteLine(0); struct S {} System.Console.WriteLine(1); System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(6, 1) ); } [Fact] public void OutOfOrder_06() { var text = @" System.Console.WriteLine(0); enum C { V } System.Console.WriteLine(1); System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(6, 1) ); } [Fact] public void OutOfOrder_07() { var text = @" System.Console.WriteLine(0); interface C {} System.Console.WriteLine(1); System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(6, 1) ); } [Fact] public void OutOfOrder_08() { var text = @" System.Console.WriteLine(0); delegate void D (); System.Console.WriteLine(1); System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,1): error CS8803: Top-level statements must precede namespace and type declarations. // System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "System.Console.WriteLine(1);").WithLocation(6, 1) ); } [Fact] public void OutOfOrder_09() { var text = @" System.Console.WriteLine(0); using System; Console.WriteLine(1); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,1): error CS1529: A using clause must precede all other elements defined in the namespace except extern alias declarations // using System; Diagnostic(ErrorCode.ERR_UsingAfterElements, "using System;").WithLocation(4, 1), // (6,1): error CS0103: The name 'Console' does not exist in the current context // Console.WriteLine(1); Diagnostic(ErrorCode.ERR_NameNotInContext, "Console").WithArguments("Console").WithLocation(6, 1) ); } [Fact] public void OutOfOrder_10() { var text = @" System.Console.WriteLine(0); [module: MyAttribute] class MyAttribute : System.Attribute {} "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,2): error CS1730: Assembly and module attributes must precede all other elements defined in a file except using clauses and extern alias declarations // [module: MyAttribute] Diagnostic(ErrorCode.ERR_GlobalAttributesNotFirst, "module").WithLocation(4, 2) ); } [Fact] public void OutOfOrder_11() { var text = @" System.Console.WriteLine(0); extern alias A; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (4,1): error CS0439: An extern alias declaration must precede all other elements defined in the namespace // extern alias A; Diagnostic(ErrorCode.ERR_ExternAfterElements, "extern").WithLocation(4, 1) ); } [Fact] public void OutOfOrder_12() { var text = @" extern alias A; using System; [module: MyAttribute] Console.WriteLine(1); class MyAttribute : System.Attribute {} "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): hidden CS8020: Unused extern alias. // extern alias A; Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias A;").WithLocation(2, 1), // (2,14): error CS0430: The extern alias 'A' was not specified in a /reference option // extern alias A; Diagnostic(ErrorCode.ERR_BadExternAlias, "A").WithArguments("A").WithLocation(2, 14) ); } [Fact] public void OutOfOrder_13() { var text = @" local(); class C {} void local() => System.Console.WriteLine(1); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (6,1): error CS8803: Top-level statements must precede namespace and type declarations. // void local() => System.Console.WriteLine(1); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "void local() => System.Console.WriteLine(1);").WithLocation(6, 1) ); } [Fact] public void Attributes_01() { var text1 = @" [MyAttribute(i)] const int i = 1; [MyAttribute(i + 1)] System.Console.Write(i); [MyAttribute(i + 2)] int j = i; System.Console.Write(j); [MyAttribute(i + 3)] new MyAttribute(i); [MyAttribute(i + 4)] local(); [MyAttribute(i + 5)] void local() {} class MyAttribute : System.Attribute { public MyAttribute(int x) {} } "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,1): error CS7014: Attributes are not valid in this context. // [MyAttribute(i)] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[MyAttribute(i)]").WithLocation(2, 1), // (5,1): error CS7014: Attributes are not valid in this context. // [MyAttribute(i + 1)] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[MyAttribute(i + 1)]").WithLocation(5, 1), // (8,1): error CS7014: Attributes are not valid in this context. // [MyAttribute(i + 2)] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[MyAttribute(i + 2)]").WithLocation(8, 1), // (12,1): error CS7014: Attributes are not valid in this context. // [MyAttribute(i + 3)] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[MyAttribute(i + 3)]").WithLocation(12, 1), // (16,1): error CS0246: The type or namespace name 'local' could not be found (are you missing a using directive or an assembly reference?) // local(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "local").WithArguments("local").WithLocation(16, 1), // (16,6): error CS1001: Identifier expected // local(); Diagnostic(ErrorCode.ERR_IdentifierExpected, "(").WithLocation(16, 6), // (16,6): error CS8112: Local function '()' must declare a body because it is not marked 'static extern'. // local(); Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "").WithArguments("()").WithLocation(16, 6), // (19,6): warning CS8321: The local function 'local' is declared but never used // void local() {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local").WithArguments("local").WithLocation(19, 6) ); var tree1 = comp.SyntaxTrees[0]; var model1 = comp.GetSemanticModel(tree1); var localDecl = tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First(); var declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.Int32 i", declSymbol.ToTestDisplayString()); var localRefs = tree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "i").ToArray(); Assert.Equal(9, localRefs.Length); foreach (var localRef in localRefs) { var refSymbol = model1.GetSymbolInfo(localRef).Symbol; Assert.Same(declSymbol, refSymbol); Assert.Contains(declSymbol.Name, model1.LookupNames(localRef.SpanStart)); Assert.Contains(declSymbol, model1.LookupSymbols(localRef.SpanStart)); Assert.Same(declSymbol, model1.LookupSymbols(localRef.SpanStart, name: declSymbol.Name).Single()); } localDecl = tree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ElementAt(1); declSymbol = model1.GetDeclaredSymbol(localDecl); Assert.Equal("System.Int32 j", declSymbol.ToTestDisplayString()); } [Fact] public void Attributes_02() { var source = @" using System.Runtime.CompilerServices; return; #pragma warning disable 8321 // Unreferenced local function [MethodImpl(MethodImplOptions.ForwardRef)] static void forwardRef() { System.Console.WriteLine(0); } [MethodImpl(MethodImplOptions.NoInlining)] static void noInlining() { System.Console.WriteLine(1); } [MethodImpl(MethodImplOptions.NoOptimization)] static void noOptimization() { System.Console.WriteLine(2); } [MethodImpl(MethodImplOptions.Synchronized)] static void synchronized() { System.Console.WriteLine(3); } [MethodImpl(MethodImplOptions.InternalCall)] extern static void internalCallStatic(); "; var verifier = CompileAndVerify( source, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: DefaultParseOptions, assemblyValidator: validateAssembly, verify: Verification.Skipped); var comp = verifier.Compilation; var syntaxTree = comp.SyntaxTrees.Single(); var semanticModel = comp.GetSemanticModel(syntaxTree); var localFunctions = syntaxTree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().ToList(); checkImplAttributes(localFunctions[0], MethodImplAttributes.ForwardRef); checkImplAttributes(localFunctions[1], MethodImplAttributes.NoInlining); checkImplAttributes(localFunctions[2], MethodImplAttributes.NoOptimization); checkImplAttributes(localFunctions[3], MethodImplAttributes.Synchronized); checkImplAttributes(localFunctions[4], MethodImplAttributes.InternalCall); void checkImplAttributes(LocalFunctionStatementSyntax localFunctionStatement, MethodImplAttributes expectedFlags) { var localFunction = semanticModel.GetDeclaredSymbol(localFunctionStatement).GetSymbol<LocalFunctionSymbol>(); Assert.Equal(expectedFlags, localFunction.ImplementationAttributes); } void validateAssembly(PEAssembly assembly) { var peReader = assembly.GetMetadataReader(); foreach (var methodHandle in peReader.MethodDefinitions) { var methodDef = peReader.GetMethodDefinition(methodHandle); var actualFlags = methodDef.ImplAttributes; var methodName = peReader.GetString(methodDef.Name); var expectedFlags = methodName switch { "<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">g__forwardRef|0_0" => MethodImplAttributes.ForwardRef, "<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">g__noInlining|0_1" => MethodImplAttributes.NoInlining, "<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">g__noOptimization|0_2" => MethodImplAttributes.NoOptimization, "<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">g__synchronized|0_3" => MethodImplAttributes.Synchronized, "<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">g__internalCallStatic|0_4" => MethodImplAttributes.InternalCall, ".ctor" => MethodImplAttributes.IL, WellKnownMemberNames.TopLevelStatementsEntryPointMethodName => MethodImplAttributes.IL, _ => throw TestExceptionUtilities.UnexpectedValue(methodName) }; Assert.Equal(expectedFlags, actualFlags); } } } [Fact] public void Attributes_03() { var source = @" using System.Runtime.InteropServices; local1(); [DllImport( ""something.dll"", EntryPoint = ""a"", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true, PreserveSig = false, CallingConvention = CallingConvention.Cdecl, BestFitMapping = false, ThrowOnUnmappableChar = true)] static extern void local1(); "; var verifier = CompileAndVerify( source, options: TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), parseOptions: DefaultParseOptions, symbolValidator: validate, verify: Verification.Skipped); var comp = verifier.Compilation; var syntaxTree = comp.SyntaxTrees.Single(); var semanticModel = comp.GetSemanticModel(syntaxTree); var localFunction = semanticModel .GetDeclaredSymbol(syntaxTree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().Single()) .GetSymbol<LocalFunctionSymbol>(); Assert.Equal(new[] { "DllImportAttribute" }, GetAttributeNames(localFunction.GetAttributes())); validateLocalFunction(localFunction); void validate(ModuleSymbol module) { var cClass = module.GlobalNamespace.GetMember<NamedTypeSymbol>(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName); Assert.Equal(new[] { "CompilerGeneratedAttribute" }, GetAttributeNames(cClass.GetAttributes().As<CSharpAttributeData>())); Assert.Empty(cClass.GetMethod(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName).GetAttributes()); var localFn1 = cClass.GetMethod("<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">g__local1|0_0"); Assert.Empty(localFn1.GetAttributes()); validateLocalFunction(localFn1); } static void validateLocalFunction(MethodSymbol localFunction) { Assert.True(localFunction.IsExtern); var importData = localFunction.GetDllImportData(); Assert.NotNull(importData); Assert.Equal("something.dll", importData.ModuleName); Assert.Equal("a", importData.EntryPointName); Assert.Equal(CharSet.Ansi, importData.CharacterSet); Assert.True(importData.SetLastError); Assert.True(importData.ExactSpelling); Assert.Equal(MethodImplAttributes.IL, localFunction.ImplementationAttributes); Assert.Equal(CallingConvention.Cdecl, importData.CallingConvention); Assert.False(importData.BestFitMapping); Assert.True(importData.ThrowOnUnmappableCharacter); } } [Fact] public void ModelWithIgnoredAccessibility_01() { var source = @" new A().M(); class A { A M() { return new A(); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,9): error CS0122: 'A.M()' is inaccessible due to its protection level // new A().M(); Diagnostic(ErrorCode.ERR_BadAccess, "M").WithArguments("A.M()").WithLocation(2, 9) ); var a = ((Compilation)comp).SourceModule.GlobalNamespace.GetTypeMember("A"); var syntaxTree = comp.SyntaxTrees.Single(); var invocation = syntaxTree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var semanticModel = comp.GetSemanticModel(syntaxTree); Assert.Equal("A", semanticModel.GetTypeInfo(invocation).Type.Name); Assert.Null(semanticModel.GetSymbolInfo(invocation).Symbol); Assert.Equal("M", semanticModel.GetSymbolInfo(invocation).CandidateSymbols.Single().Name); Assert.Equal(CandidateReason.Inaccessible, semanticModel.GetSymbolInfo(invocation).CandidateReason); Assert.Empty(semanticModel.LookupSymbols(invocation.SpanStart, container: a, name: "M")); semanticModel = comp.GetSemanticModel(syntaxTree, ignoreAccessibility: true); Assert.Equal("A", semanticModel.GetTypeInfo(invocation).Type.Name); Assert.Equal("M", semanticModel.GetSymbolInfo(invocation).Symbol.Name); Assert.NotEmpty(semanticModel.LookupSymbols(invocation.SpanStart, container: a, name: "M")); } [Fact] public void ModelWithIgnoredAccessibility_02() { var source = @" var x = new A().M(); class A { A M() { x = null; return new A(); } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (2,17): error CS0122: 'A.M()' is inaccessible due to its protection level // var x = new A().M(); Diagnostic(ErrorCode.ERR_BadAccess, "M").WithArguments("A.M()").WithLocation(2, 17), // (8,9): error CS8801: Cannot use local variable or local function 'x' declared in a top-level statement in this context. // x = null; Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "x").WithArguments("x").WithLocation(8, 9) ); var a = ((Compilation)comp).SourceModule.GlobalNamespace.GetTypeMember("A"); var syntaxTree = comp.SyntaxTrees.Single(); var localDecl = syntaxTree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var localRef = syntaxTree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Single(); var semanticModel = comp.GetSemanticModel(syntaxTree, ignoreAccessibility: true); var x = semanticModel.GetDeclaredSymbol(localDecl); Assert.Same(x, semanticModel.LookupSymbols(localDecl.SpanStart, name: "x").Single()); Assert.Same(x, semanticModel.GetSymbolInfo(localRef).Symbol); Assert.Same(x, semanticModel.LookupSymbols(localRef.SpanStart, name: "x").Single()); } [Fact] public void ModelWithIgnoredAccessibility_03() { var source = @" var x = new B().M(1); class A { public long M(long i) => i; } class B : A { protected int M(int i) { _ = x; return i; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (13,13): error CS8801: Cannot use local variable or local function 'x' declared in a top-level statement in this context. // _ = x; Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "x").WithArguments("x").WithLocation(13, 13) ); var a = ((Compilation)comp).SourceModule.GlobalNamespace.GetTypeMember("A"); var syntaxTree1 = comp.SyntaxTrees.Single(); var localDecl = syntaxTree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var localRef = syntaxTree1.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Single(); verifyModel(ignoreAccessibility: true, "System.Int32"); verifyModel(ignoreAccessibility: false, "System.Int64"); void verifyModel(bool ignoreAccessibility, string expectedType) { var semanticModel1 = comp.GetSemanticModel(syntaxTree1, ignoreAccessibility); var xDecl = semanticModel1.GetDeclaredSymbol(localDecl); Assert.Same(xDecl, semanticModel1.LookupSymbols(localDecl.SpanStart, name: "x").Single()); var xRef = semanticModel1.GetSymbolInfo(localRef).Symbol; Assert.Same(xRef, semanticModel1.LookupSymbols(localRef.SpanStart, name: "x").Single()); Assert.Equal(expectedType, ((ILocalSymbol)xRef).Type.ToTestDisplayString()); Assert.Equal(expectedType, ((ILocalSymbol)xDecl).Type.ToTestDisplayString()); Assert.Same(xDecl, xRef); } } [Fact] public void ModelWithIgnoredAccessibility_04() { var source1 = @" var x = new B().M(1); "; var source2 = @" class A { public long M(long i) => i; } class B : A { protected int M(int i) { _ = x; return i; } } "; var comp = CreateCompilation(new[] { source1, source2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (11,13): error CS8801: Cannot use local variable or local function 'x' declared in a top-level statement in this context. // _ = x; Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "x").WithArguments("x").WithLocation(11, 13) ); var a = ((Compilation)comp).SourceModule.GlobalNamespace.GetTypeMember("A"); var syntaxTree1 = comp.SyntaxTrees.First(); var localDecl = syntaxTree1.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var syntaxTree2 = comp.SyntaxTrees[1]; var localRef = syntaxTree2.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "x").Single(); verifyModel(ignoreAccessibility: true, "System.Int32"); verifyModel(ignoreAccessibility: false, "System.Int64"); void verifyModel(bool ignoreAccessibility, string expectedType) { var semanticModel1 = comp.GetSemanticModel(syntaxTree1, ignoreAccessibility); var xDecl = semanticModel1.GetDeclaredSymbol(localDecl); Assert.Same(xDecl, semanticModel1.LookupSymbols(localDecl.SpanStart, name: "x").Single()); Assert.Equal(expectedType, ((ILocalSymbol)xDecl).Type.ToTestDisplayString()); var semanticModel2 = comp.GetSemanticModel(syntaxTree2, ignoreAccessibility); var xRef = semanticModel2.GetSymbolInfo(localRef).Symbol; Assert.Same(xRef, semanticModel2.LookupSymbols(localRef.SpanStart, name: "x").Single()); Assert.Equal(expectedType, ((ILocalSymbol)xRef).Type.ToTestDisplayString()); Assert.Same(xDecl, xRef); } } [Fact] public void AnalyzerActions_01() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_01_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(0, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(0, analyzer.FireCount6); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_01_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); } private class AnalyzerActions_01_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.GlobalStatement); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.CompilationUnit); } private void Handle1(SyntaxNodeAnalysisContext context) { var model = context.SemanticModel; var globalStatement = (GlobalStatementSyntax)context.Node; var syntaxTreeModel = ((SyntaxTreeSemanticModel)model); switch (globalStatement.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } Assert.Equal("<top-level-statements-entry-point>", context.ContainingSymbol.ToTestDisplayString()); Assert.Same(globalStatement.SyntaxTree, context.ContainingSymbol.DeclaringSyntaxReferences.Single().SyntaxTree); Assert.True(syntaxTreeModel.TestOnlyMemberModels.ContainsKey(globalStatement.Parent)); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[globalStatement.Parent]; Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(globalStatement.Statement).IsDefaultOrEmpty); Assert.Same(mm, syntaxTreeModel.GetMemberModel(globalStatement.Statement)); } private void Handle2(SyntaxNodeAnalysisContext context) { var model = context.SemanticModel; var unit = (CompilationUnitSyntax)context.Node; var syntaxTreeModel = ((SyntaxTreeSemanticModel)model); switch (unit.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref context.ContainingSymbol.Kind == SymbolKind.Namespace ? ref FireCount5 : ref FireCount3); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref context.ContainingSymbol.Kind == SymbolKind.Namespace ? ref FireCount6 : ref FireCount4); break; default: Assert.True(false); break; } switch (context.ContainingSymbol.ToTestDisplayString()) { case "<top-level-statements-entry-point>": Assert.Same(unit.SyntaxTree, context.ContainingSymbol.DeclaringSyntaxReferences.Single().SyntaxTree); Assert.True(syntaxTreeModel.TestOnlyMemberModels.ContainsKey(unit)); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[unit]; Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(unit).IsDefaultOrEmpty); Assert.Same(mm, syntaxTreeModel.GetMemberModel(unit)); break; case "<global namespace>": break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_02() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_02_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_02_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); } private class AnalyzerActions_02_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(Handle, SymbolKind.Method); } private void Handle(SymbolAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.Symbol.ToTestDisplayString()); switch (context.Symbol.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_03() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_03_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(0, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(0, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_03_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); } private class AnalyzerActions_03_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; public int FireCount8; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolStartAction(Handle1, SymbolKind.Method); context.RegisterSymbolStartAction(Handle2, SymbolKind.NamedType); } private void Handle1(SymbolStartAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.Symbol.ToTestDisplayString()); switch (context.Symbol.DeclaringSyntaxReferences.Single().GetSyntax().ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); context.RegisterSymbolEndAction(Handle3); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); context.RegisterSymbolEndAction(Handle4); break; default: Assert.True(false); break; } } private void Handle2(SymbolStartAnalysisContext context) { Assert.Equal(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName, context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount3); context.RegisterSymbolEndAction(Handle5); foreach (var syntaxReference in context.Symbol.DeclaringSyntaxReferences) { switch (syntaxReference.GetSyntax().ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount4); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount5); break; default: Assert.True(false); break; } } } private void Handle3(SymbolAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount6); Assert.Equal("System.Console.WriteLine(1);", context.Symbol.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); } private void Handle4(SymbolAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount7); Assert.Equal("System.Console.WriteLine(2);", context.Symbol.DeclaringSyntaxReferences.Single().GetSyntax().ToString()); } private void Handle5(SymbolAnalysisContext context) { Assert.Equal(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName, context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount8); } } [Fact] public void AnalyzerActions_04() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_04_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(0, analyzer.FireCount4); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_04_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); } private class AnalyzerActions_04_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationAction(Handle1, OperationKind.Invocation); context.RegisterOperationAction(Handle2, OperationKind.Block); } private void Handle1(OperationAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.ContainingSymbol.ToTestDisplayString()); Assert.Same(context.ContainingSymbol.DeclaringSyntaxReferences.Single().SyntaxTree, context.Operation.Syntax.SyntaxTree); Assert.Equal(SyntaxKind.InvocationExpression, context.Operation.Syntax.Kind()); switch (context.Operation.Syntax.ToString()) { case "System.Console.WriteLine(1)": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2)": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } } private void Handle2(OperationAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.ContainingSymbol.ToTestDisplayString()); Assert.Same(context.ContainingSymbol.DeclaringSyntaxReferences.Single().GetSyntax(), context.Operation.Syntax); Assert.Equal(SyntaxKind.CompilationUnit, context.Operation.Syntax.Kind()); switch (context.Operation.Syntax.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount3); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount4); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_05() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_05_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_05_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); } private class AnalyzerActions_05_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockAction(Handle); } private void Handle(OperationBlockAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.OwningSymbol.ToTestDisplayString()); Assert.Equal(SyntaxKind.CompilationUnit, context.OperationBlocks.Single().Syntax.Kind()); switch (context.OperationBlocks.Single().Syntax.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_06() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_06_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_06_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); } private class AnalyzerActions_06_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockStartAction(Handle); } private void Handle(OperationBlockStartAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.OwningSymbol.ToTestDisplayString()); Assert.Equal(SyntaxKind.CompilationUnit, context.OperationBlocks.Single().Syntax.Kind()); switch (context.OperationBlocks.Single().Syntax.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_07() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_07_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_07_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); } private class AnalyzerActions_07_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockAction(Handle); } private void Handle(CodeBlockAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.OwningSymbol.ToTestDisplayString()); Assert.Equal(SyntaxKind.CompilationUnit, context.CodeBlock.Kind()); switch (context.CodeBlock.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } var model = context.SemanticModel; var unit = (CompilationUnitSyntax)context.CodeBlock; var syntaxTreeModel = ((SyntaxTreeSemanticModel)model); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[unit]; Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(unit).IsDefaultOrEmpty); Assert.Same(mm, syntaxTreeModel.GetMemberModel(unit)); } } [Fact] public void AnalyzerActions_08() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_08_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_08_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); } private class AnalyzerActions_08_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockStartAction<SyntaxKind>(Handle); } private void Handle(CodeBlockStartAnalysisContext<SyntaxKind> context) { Assert.Equal("<top-level-statements-entry-point>", context.OwningSymbol.ToTestDisplayString()); Assert.Equal(SyntaxKind.CompilationUnit, context.CodeBlock.Kind()); switch (context.CodeBlock.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } var model = context.SemanticModel; var unit = (CompilationUnitSyntax)context.CodeBlock; var syntaxTreeModel = ((SyntaxTreeSemanticModel)model); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[unit]; Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(unit).IsDefaultOrEmpty); Assert.Same(mm, syntaxTreeModel.GetMemberModel(unit)); } } [Fact] public void AnalyzerActions_09() { var text1 = @" System.Console.WriteLine(""Hi!""); "; var text2 = @" class Test { void M() { M(); } } "; var analyzer = new AnalyzerActions_09_Analyzer(); var comp = CreateCompilation(text1 + text2, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); analyzer = new AnalyzerActions_09_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(2, analyzer.FireCount4); } private class AnalyzerActions_09_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.InvocationExpression); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.CompilationUnit); } private void Handle1(SyntaxNodeAnalysisContext context) { var model = context.SemanticModel; var node = (CSharpSyntaxNode)context.Node; var syntaxTreeModel = ((SyntaxTreeSemanticModel)model); switch (node.ToString()) { case @"System.Console.WriteLine(""Hi!"")": Interlocked.Increment(ref FireCount1); Assert.Equal("<top-level-statements-entry-point>", context.ContainingSymbol.ToTestDisplayString()); break; case "M()": Interlocked.Increment(ref FireCount2); Assert.Equal("void Test.M()", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } var decl = (CSharpSyntaxNode)context.ContainingSymbol.DeclaringSyntaxReferences.Single().GetSyntax(); Assert.True(syntaxTreeModel.TestOnlyMemberModels.ContainsKey(decl)); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[decl]; Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(node).IsDefaultOrEmpty); Assert.Same(mm, syntaxTreeModel.GetMemberModel(node)); } private void Handle2(SyntaxNodeAnalysisContext context) { var model = context.SemanticModel; var node = (CSharpSyntaxNode)context.Node; var syntaxTreeModel = ((SyntaxTreeSemanticModel)model); switch (context.ContainingSymbol.ToTestDisplayString()) { case @"<top-level-statements-entry-point>": Interlocked.Increment(ref FireCount3); Assert.True(syntaxTreeModel.TestOnlyMemberModels.ContainsKey(node)); MemberSemanticModel mm = syntaxTreeModel.TestOnlyMemberModels[node]; Assert.False(mm.TestOnlyTryGetBoundNodesFromMap(node).IsDefaultOrEmpty); Assert.Same(mm, syntaxTreeModel.GetMemberModel(node)); break; case "<global namespace>": Interlocked.Increment(ref FireCount4); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_10() { var text1 = @" [assembly: MyAttribute(1)] "; var text2 = @" System.Console.WriteLine(""Hi!""); "; var text3 = @" [MyAttribute(2)] class Test { [MyAttribute(3)] void M() { } } class MyAttribute : System.Attribute { public MyAttribute(int x) {} } "; var analyzer = new AnalyzerActions_10_Analyzer(); var comp = CreateCompilation(text1 + text2 + text3, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); analyzer = new AnalyzerActions_10_Analyzer(); comp = CreateCompilation(new[] { text1, text2, text3 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(3, analyzer.FireCount5); } private class AnalyzerActions_10_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.Attribute); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.CompilationUnit); } private void Handle1(SyntaxNodeAnalysisContext context) { var node = (CSharpSyntaxNode)context.Node; switch (node.ToString()) { case @"MyAttribute(1)": Interlocked.Increment(ref FireCount1); Assert.Equal("<global namespace>", context.ContainingSymbol.ToTestDisplayString()); break; case @"MyAttribute(2)": Interlocked.Increment(ref FireCount2); Assert.Equal("Test", context.ContainingSymbol.ToTestDisplayString()); break; case @"MyAttribute(3)": Interlocked.Increment(ref FireCount3); Assert.Equal("void Test.M()", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } } private void Handle2(SyntaxNodeAnalysisContext context) { switch (context.ContainingSymbol.ToTestDisplayString()) { case @"<top-level-statements-entry-point>": Interlocked.Increment(ref FireCount4); break; case @"<global namespace>": Interlocked.Increment(ref FireCount5); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_11() { var text1 = @" System.Console.WriteLine(""Hi!""); "; var text2 = @" namespace N1 {} class C1 {} "; var analyzer = new AnalyzerActions_11_Analyzer(); var comp = CreateCompilation(text1 + text2, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); analyzer = new AnalyzerActions_11_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); } private class AnalyzerActions_11_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(Handle1, SymbolKind.Method); context.RegisterSymbolAction(Handle2, SymbolKind.Namespace); context.RegisterSymbolAction(Handle3, SymbolKind.NamedType); } private void Handle1(SymbolAnalysisContext context) { Interlocked.Increment(ref FireCount1); Assert.Equal("<top-level-statements-entry-point>", context.Symbol.ToTestDisplayString()); } private void Handle2(SymbolAnalysisContext context) { Interlocked.Increment(ref FireCount2); Assert.Equal("N1", context.Symbol.ToTestDisplayString()); } private void Handle3(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "C1": Interlocked.Increment(ref FireCount3); break; case WellKnownMemberNames.TopLevelStatementsEntryPointTypeName: Interlocked.Increment(ref FireCount4); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_12() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_12_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_12_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(2, analyzer.FireCount3); } private class AnalyzerActions_12_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockStartAction(Handle1); } private void Handle1(OperationBlockStartAnalysisContext context) { Interlocked.Increment(ref FireCount3); context.RegisterOperationBlockEndAction(Handle2); } private void Handle2(OperationBlockAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.OwningSymbol.ToTestDisplayString()); Assert.Equal(SyntaxKind.CompilationUnit, context.OperationBlocks.Single().Syntax.Kind()); switch (context.OperationBlocks.Single().Syntax.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_13() { var text1 = @"System.Console.WriteLine(1);"; var analyzer = new AnalyzerActions_13_Analyzer(); var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(0, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); var text2 = @"System.Console.WriteLine(2);"; analyzer = new AnalyzerActions_13_Analyzer(); comp = CreateCompilation(new[] { text1, text2 }, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(2, analyzer.FireCount3); } private class AnalyzerActions_13_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockStartAction(Handle1); } private void Handle1(OperationBlockStartAnalysisContext context) { Interlocked.Increment(ref FireCount3); context.RegisterOperationAction(Handle2, OperationKind.Block); } private void Handle2(OperationAnalysisContext context) { Assert.Equal("<top-level-statements-entry-point>", context.ContainingSymbol.ToTestDisplayString()); Assert.Same(context.ContainingSymbol.DeclaringSyntaxReferences.Single().GetSyntax(), context.Operation.Syntax); Assert.Equal(SyntaxKind.CompilationUnit, context.Operation.Syntax.Kind()); switch (context.Operation.Syntax.ToString()) { case "System.Console.WriteLine(1);": Interlocked.Increment(ref FireCount1); break; case "System.Console.WriteLine(2);": Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } } } [Fact] public void MissingTypes_01() { var text = @"return;"; var comp = CreateEmptyCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1), // error CS0518: Predefined type 'System.Object' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Object").WithLocation(1, 1), // error CS0518: Predefined type 'System.Void' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Void").WithLocation(1, 1), // error CS0518: Predefined type 'System.String' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.String").WithLocation(1, 1) ); } [Fact] public void MissingTypes_02() { var text = @"await Test();"; var comp = CreateCompilation(text, targetFramework: TargetFramework.Minimal, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // error CS0518: Predefined type 'System.Threading.Tasks.Task' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Threading.Tasks.Task").WithLocation(1, 1), // (1,1): warning CS0028: '<top-level-statements-entry-point>' has the wrong signature to be an entry point // await Test(); Diagnostic(ErrorCode.WRN_InvalidMainSig, "await Test();").WithArguments("<top-level-statements-entry-point>").WithLocation(1, 1), // error CS5001: Program does not contain a static 'Main' method suitable for an entry point Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1), // (1,7): error CS0103: The name 'Test' does not exist in the current context // await Test(); Diagnostic(ErrorCode.ERR_NameNotInContext, "Test").WithArguments("Test").WithLocation(1, 7) ); } [Fact] public void MissingTypes_03() { var text = @" System.Console.WriteLine(""Hi!""); return 10; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.MakeTypeMissing(SpecialType.System_Int32); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Int32[missing]", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); comp.VerifyEmitDiagnostics( // error CS0518: Predefined type 'System.Int32' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Int32").WithLocation(1, 1), // (3,8): error CS0518: Predefined type 'System.Int32' is not defined or imported // return 10; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "10").WithArguments("System.Int32").WithLocation(3, 8) ); } [Fact] public void MissingTypes_04() { var text = @" await System.Threading.Tasks.Task.Factory.StartNew(() => 5L); return 11; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.MakeTypeMissing(SpecialType.System_Int32); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task<System.Int32[missing]>", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); comp.VerifyEmitDiagnostics( // error CS0518: Predefined type 'System.Int32' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Int32").WithLocation(1, 1), // error CS5001: Program does not contain a static 'Main' method suitable for an entry point Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1), // (2,1): warning CS0028: '<top-level-statements-entry-point>' has the wrong signature to be an entry point // await System.Threading.Tasks.Task.Factory.StartNew(() => 5L); Diagnostic(ErrorCode.WRN_InvalidMainSig, @"await System.Threading.Tasks.Task.Factory.StartNew(() => 5L); return 11; ").WithArguments("<top-level-statements-entry-point>").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Int32' is not defined or imported // await System.Threading.Tasks.Task.Factory.StartNew(() => 5L); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await System.Threading.Tasks.Task.Factory.StartNew(() => 5L);").WithArguments("System.Int32").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Int32' is not defined or imported // await System.Threading.Tasks.Task.Factory.StartNew(() => 5L); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await System.Threading.Tasks.Task.Factory.StartNew(() => 5L);").WithArguments("System.Int32").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Int32' is not defined or imported // await System.Threading.Tasks.Task.Factory.StartNew(() => 5L); Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await System.Threading.Tasks.Task.Factory.StartNew(() => 5L);").WithArguments("System.Int32").WithLocation(2, 1), // (3,8): error CS0518: Predefined type 'System.Int32' is not defined or imported // return 11; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "11").WithArguments("System.Int32").WithLocation(3, 8) ); } [Fact] public void MissingTypes_05() { var text = @" await System.Threading.Tasks.Task.Factory.StartNew(() => ""5""); return 11; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.MakeTypeMissing(WellKnownType.System_Threading_Tasks_Task_T); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task<System.Int32>[missing]", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); comp.VerifyEmitDiagnostics( // error CS0518: Predefined type 'System.Threading.Tasks.Task`1' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Threading.Tasks.Task`1").WithLocation(1, 1), // error CS5001: Program does not contain a static 'Main' method suitable for an entry point Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1), // (2,1): warning CS0028: '<top-level-statements-entry-point>' has the wrong signature to be an entry point // await System.Threading.Tasks.Task.Factory.StartNew(() => "5"); Diagnostic(ErrorCode.WRN_InvalidMainSig, @"await System.Threading.Tasks.Task.Factory.StartNew(() => ""5""); return 11; ").WithArguments("<top-level-statements-entry-point>").WithLocation(2, 1) ); } [Fact] public void MissingTypes_06() { var text = @" await System.Threading.Tasks.Task.Factory.StartNew(() => ""5""); return 11; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.MakeTypeMissing(SpecialType.System_Int32); comp.MakeTypeMissing(WellKnownType.System_Threading_Tasks_Task_T); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task<System.Int32[missing]>[missing]", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); comp.VerifyEmitDiagnostics( // error CS0518: Predefined type 'System.Threading.Tasks.Task`1' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Threading.Tasks.Task`1").WithLocation(1, 1), // error CS0518: Predefined type 'System.Int32' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Int32").WithLocation(1, 1), // error CS5001: Program does not contain a static 'Main' method suitable for an entry point Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1), // (2,1): warning CS0028: '<top-level-statements-entry-point>' has the wrong signature to be an entry point // await System.Threading.Tasks.Task.Factory.StartNew(() => "5"); Diagnostic(ErrorCode.WRN_InvalidMainSig, @"await System.Threading.Tasks.Task.Factory.StartNew(() => ""5""); return 11; ").WithArguments("<top-level-statements-entry-point>").WithLocation(2, 1), // (3,8): error CS0518: Predefined type 'System.Int32' is not defined or imported // return 11; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "11").WithArguments("System.Int32").WithLocation(3, 8) ); } [Fact] public void MissingTypes_07() { var text = @" System.Console.WriteLine(); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.MakeTypeMissing(SpecialType.System_String); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.String[missing][] args", entryPoint.Parameters.Single().ToTestDisplayString()); comp.VerifyEmitDiagnostics( // error CS0518: Predefined type 'System.String' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.String").WithLocation(1, 1) ); } [Fact] public void Return_01() { var text = @" System.Console.WriteLine(args[0]); return; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); Assert.True(entryPoint.ReturnsVoid); AssertEntryPointParameter(entryPoint); CompileAndVerify(comp, expectedOutput: "Return_01", args: new[] { "Return_01" }); if (ExecutionConditionUtil.IsWindows) { _ = ConditionalSkipReason.NativePdbRequiresDesktop; comp.VerifyPdb(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + "." + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName, @$"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" methodName=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }"" parameterNames=""args"" /> <methods> <method containingType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" name=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""2"" startColumn=""1"" endLine=""2"" endColumn=""35"" document=""1"" /> <entry offset=""0x9"" startLine=""3"" startColumn=""1"" endLine=""3"" endColumn=""8"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>", options: PdbValidationOptions.SkipConversionValidation); } } private static string EscapeForXML(string toEscape) { return toEscape.Replace("<", "&lt;").Replace(">", "&gt;"); } [Fact] public void Return_02() { var text = @" System.Console.WriteLine(args[0]); return 10; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Int32", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); AssertEntryPointParameter(entryPoint); CompileAndVerify(comp, expectedOutput: "Return_02", args: new[] { "Return_02" }, expectedReturnCode: 10); if (ExecutionConditionUtil.IsWindows) { _ = ConditionalSkipReason.NativePdbRequiresDesktop; comp.VerifyPdb(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + "." + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName, @$"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" methodName=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }"" parameterNames=""args"" /> <methods> <method containingType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" name=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""2"" startColumn=""1"" endLine=""2"" endColumn=""35"" document=""1"" /> <entry offset=""0x9"" startLine=""3"" startColumn=""1"" endLine=""3"" endColumn=""11"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>", options: PdbValidationOptions.SkipConversionValidation); } } [Fact] public void Return_03() { var text = @" using System; using System.Threading.Tasks; Console.Write(""hello ""); await Task.Factory.StartNew(() => 5); Console.Write(args[0]); return; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); AssertEntryPointParameter(entryPoint); CompileAndVerify(comp, expectedOutput: "hello Return_03", args: new[] { "Return_03" }); if (ExecutionConditionUtil.IsWindows) { _ = ConditionalSkipReason.NativePdbRequiresDesktop; comp.VerifyPdb(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + "+<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">d__0.MoveNext", @$"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" methodName=""&lt;Main&gt;"" parameterNames=""args"" /> <methods> <method containingType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }+&lt;{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }+&lt;&gt;c"" methodName=""&lt;{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }&gt;b__0_0"" /> <encLocalSlotMap> <slot kind=""27"" offset=""2"" /> <slot kind=""33"" offset=""76"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0xe"" startLine=""5"" startColumn=""1"" endLine=""5"" endColumn=""25"" document=""1"" /> <entry offset=""0x19"" startLine=""6"" startColumn=""1"" endLine=""6"" endColumn=""38"" document=""1"" /> <entry offset=""0x48"" hidden=""true"" document=""1"" /> <entry offset=""0x99"" startLine=""7"" startColumn=""1"" endLine=""7"" endColumn=""24"" document=""1"" /> <entry offset=""0xa7"" startLine=""8"" startColumn=""1"" endLine=""8"" endColumn=""8"" document=""1"" /> <entry offset=""0xa9"" hidden=""true"" document=""1"" /> <entry offset=""0xc1"" hidden=""true"" document=""1"" /> </sequencePoints> <asyncInfo> <catchHandler offset=""0xa9"" /> <kickoffMethod declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" methodName=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }"" parameterNames=""args"" /> <await yield=""0x5a"" resume=""0x75"" declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }+&lt;{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }&gt;d__0"" methodName=""MoveNext"" /> </asyncInfo> </method> </methods> </symbols>", options: PdbValidationOptions.SkipConversionValidation); } } [Fact] public void Return_04() { var text = @" using System; using System.Threading.Tasks; Console.Write(""hello ""); await Task.Factory.StartNew(() => 5); Console.Write(args[0]); return 11; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task<System.Int32>", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); AssertEntryPointParameter(entryPoint); CompileAndVerify(comp, expectedOutput: "hello Return_04", args: new[] { "Return_04" }, expectedReturnCode: 11); if (ExecutionConditionUtil.IsWindows) { _ = ConditionalSkipReason.NativePdbRequiresDesktop; comp.VerifyPdb(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + "+<" + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName + ">d__0.MoveNext", @$"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <entryPoint declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" methodName=""&lt;Main&gt;"" parameterNames=""args"" /> <methods> <method containingType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }+&lt;{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }&gt;d__0"" name=""MoveNext""> <customDebugInfo> <forward declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }+&lt;&gt;c"" methodName=""&lt;{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }&gt;b__0_0"" /> <encLocalSlotMap> <slot kind=""27"" offset=""2"" /> <slot kind=""20"" offset=""2"" /> <slot kind=""33"" offset=""76"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" hidden=""true"" document=""1"" /> <entry offset=""0x7"" hidden=""true"" document=""1"" /> <entry offset=""0xe"" startLine=""5"" startColumn=""1"" endLine=""5"" endColumn=""25"" document=""1"" /> <entry offset=""0x19"" startLine=""6"" startColumn=""1"" endLine=""6"" endColumn=""38"" document=""1"" /> <entry offset=""0x48"" hidden=""true"" document=""1"" /> <entry offset=""0x99"" startLine=""7"" startColumn=""1"" endLine=""7"" endColumn=""24"" document=""1"" /> <entry offset=""0xa7"" startLine=""8"" startColumn=""1"" endLine=""8"" endColumn=""11"" document=""1"" /> <entry offset=""0xac"" hidden=""true"" document=""1"" /> <entry offset=""0xc6"" hidden=""true"" document=""1"" /> </sequencePoints> <asyncInfo> <catchHandler offset=""0xac"" /> <kickoffMethod declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }"" methodName=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }"" parameterNames=""args"" /> <await yield=""0x5a"" resume=""0x75"" declaringType=""{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) }+&lt;{ EscapeForXML(WellKnownMemberNames.TopLevelStatementsEntryPointMethodName) }&gt;d__0"" methodName=""MoveNext"" /> </asyncInfo> </method> </methods> </symbols>", options: PdbValidationOptions.SkipConversionValidation); } } [Fact] public void Return_05() { var text = @" System.Console.WriteLine(""Hi!""); return ""error""; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Int32", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); comp.VerifyDiagnostics( // (3,8): error CS0029: Cannot implicitly convert type 'string' to 'int' // return "error"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""error""").WithArguments("string", "int").WithLocation(3, 8) ); } [Fact] public void Return_06() { var text = @" System.Func<int, int> d = n => { System.Console.WriteLine(""Hi!""); return n; }; d(0); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); Assert.True(entryPoint.ReturnsVoid); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void Return_07() { var text = @" System.Func<int, int> d = delegate(int n) { System.Console.WriteLine(""Hi!""); return n; }; d(0); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); Assert.True(entryPoint.ReturnsVoid); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void Return_08() { var text = @" System.Func<int, int> d = (n) => { System.Console.WriteLine(""Hi!""); return n; }; d(0); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); Assert.True(entryPoint.ReturnsVoid); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void Return_09() { var text = @" int local(int n) { System.Console.WriteLine(""Hi!""); return n; } local(0); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); Assert.True(entryPoint.ReturnsVoid); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void Return_10() { var text = @" bool b = true; if (b) return 0; else return; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Int32", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); comp.VerifyDiagnostics( // (6,5): error CS0126: An object of a type convertible to 'int' is required // return; Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("int").WithLocation(6, 5) ); } [Fact] public void Return_11() { var text = @" bool b = true; if (b) return; else return 0; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Int32", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); comp.VerifyDiagnostics( // (4,5): error CS0126: An object of a type convertible to 'int' is required // return; Diagnostic(ErrorCode.ERR_RetObjectRequired, "return").WithArguments("int").WithLocation(4, 5) ); } [Fact] public void Return_12() { var text = @" System.Console.WriteLine(1); return; System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Void", entryPoint.ReturnType.ToTestDisplayString()); CompileAndVerify(comp, expectedOutput: "1").VerifyDiagnostics( // (4,1): warning CS0162: Unreachable code detected // System.Console.WriteLine(2); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(4, 1) ); } [Fact] public void Return_13() { var text = @" System.Console.WriteLine(1); return 13; System.Console.WriteLine(2); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Int32", entryPoint.ReturnType.ToTestDisplayString()); CompileAndVerify(comp, expectedOutput: "1", expectedReturnCode: 13).VerifyDiagnostics( // (4,1): warning CS0162: Unreachable code detected // System.Console.WriteLine(2); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(4, 1) ); } [Fact] public void Return_14() { var text = @" System.Console.WriteLine(""Hi!""); return default; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Int32", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); CompileAndVerify(comp, expectedOutput: "Hi!", expectedReturnCode: 0); } [Fact] public void Return_15() { var text = @" using System; using System.Threading.Tasks; Console.Write(""hello ""); await Task.Factory.StartNew(() => 5); Console.Write(""async main""); return default; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); Assert.Equal("System.Threading.Tasks.Task<System.Int32>", entryPoint.ReturnType.ToTestDisplayString()); Assert.False(entryPoint.ReturnsVoid); CompileAndVerify(comp, expectedOutput: "hello async main", expectedReturnCode: 0); } [Fact] public void Dll_01() { var text = @"System.Console.WriteLine(""Hi!"");"; var comp = CreateCompilation(text, options: TestOptions.DebugDll, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // (1,1): error CS8805: Program using top-level statements must be an executable. // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, @"System.Console.WriteLine(""Hi!"");").WithLocation(1, 1) ); } [Fact] public void NetModule_01() { var text = @"System.Console.WriteLine(""Hi!"");"; var comp = CreateCompilation(text, options: TestOptions.ReleaseModule, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // (1,1): error CS8805: Program using top-level statements must be an executable. // System.Console.WriteLine("Hi!"); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, @"System.Console.WriteLine(""Hi!"");").WithLocation(1, 1) ); } [Fact] public void ExpressionStatement_01() { // Await expression is covered in other tests var text = @" new Test(0); // ObjectCreationExpression: Test x; x = new Test(1); // SimpleAssignmentExpression: x += 1; // AddAssignmentExpression: x -= 2; // SubtractAssignmentExpression: x *= 3; // MultiplyAssignmentExpression: x /= 4; // DivideAssignmentExpression: x %= 5; // ModuloAssignmentExpression: x &= 6; // AndAssignmentExpression: x |= 7; // OrAssignmentExpression: x ^= 8; // ExclusiveOrAssignmentExpression: x <<= 9; // LeftShiftAssignmentExpression: x >>= 10; // RightShiftAssignmentExpression: x++; // PostIncrementExpression: x--; // PostDecrementExpression: ++x; // PreIncrementExpression: --x; // PreDecrementExpression: System.Console.WriteLine(x.Count); // InvocationExpression: x?.WhenNotNull(); // ConditionalAccessExpression: x = null; x ??= new Test(-1); // CoalesceAssignmentExpression: System.Console.WriteLine(x.Count); // InvocationExpression: class Test { public readonly int Count; public Test(int count) { Count = count; if (count == 0) { System.Console.WriteLine(""Test..ctor""); } } public static Test operator +(Test x, int y) { return new Test(x.Count + 1); } public static Test operator -(Test x, int y) { return new Test(x.Count + 1); } public static Test operator *(Test x, int y) { return new Test(x.Count + 1); } public static Test operator /(Test x, int y) { return new Test(x.Count + 1); } public static Test operator %(Test x, int y) { return new Test(x.Count + 1); } public static Test operator &(Test x, int y) { return new Test(x.Count + 1); } public static Test operator |(Test x, int y) { return new Test(x.Count + 1); } public static Test operator ^(Test x, int y) { return new Test(x.Count + 1); } public static Test operator <<(Test x, int y) { return new Test(x.Count + 1); } public static Test operator >>(Test x, int y) { return new Test(x.Count + 1); } public static Test operator ++(Test x) { return new Test(x.Count + 1); } public static Test operator --(Test x) { return new Test(x.Count + 1); } public void WhenNotNull() { System.Console.WriteLine(""WhenNotNull""); } } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: @"Test..ctor 15 WhenNotNull -1 "); } [Fact] public void Block_01() { var text = @" { System.Console.WriteLine(""Hi!""); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void EmptyStatement_01() { var text = @" ; System.Console.WriteLine(""Hi!""); ; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void BreakStatement_01() { var text = @"break;"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS0139: No enclosing loop out of which to break or continue // break; Diagnostic(ErrorCode.ERR_NoBreakOrCont, "break;").WithLocation(1, 1) ); } [Fact] public void ContinueStatement_01() { var text = @"continue;"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS0139: No enclosing loop out of which to break or continue // continue; Diagnostic(ErrorCode.ERR_NoBreakOrCont, "continue;").WithLocation(1, 1) ); } [Fact] public void ThrowStatement_01() { var text = @"throw;"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause // throw; Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw").WithLocation(1, 1) ); } [Fact] public void ThrowStatement_02() { var text = @"throw null;"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp).VerifyIL("<top-level-statements-entry-point>", sequencePoints: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + "." + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName, source: text, expectedIL: @" { // Code size 2 (0x2) .maxstack 1 // sequence point: throw null; IL_0000: ldnull IL_0001: throw } "); } [Fact] public void DoStatement_01() { var text = @" int i = 1; do { i++; } while (i < 4); System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "4"); } [Fact] public void WhileStatement_01() { var text = @" int i = 1; while (i < 4) { i++; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "4"); } [Fact] public void ForStatement_01() { var text = @" int i = 1; for (;i < 4;) { i++; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "4"); } [Fact] public void CheckedStatement_01() { var text = @" int i = 1; i++; checked { i++; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "3").VerifyIL("<top-level-statements-entry-point>", sequencePoints: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + "." + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName, source: text, expectedIL: @" { // Code size 20 (0x14) .maxstack 2 .locals init (int V_0) //i // sequence point: int i = 1; IL_0000: ldc.i4.1 IL_0001: stloc.0 // sequence point: i++; IL_0002: ldloc.0 IL_0003: ldc.i4.1 IL_0004: add IL_0005: stloc.0 // sequence point: { IL_0006: nop // sequence point: i++; IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: add.ovf IL_000a: stloc.0 // sequence point: } IL_000b: nop // sequence point: System.Console.WriteLine(i); IL_000c: ldloc.0 IL_000d: call ""void System.Console.WriteLine(int)"" IL_0012: nop IL_0013: ret } "); } [Fact] public void UncheckedStatement_01() { var text = @" int i = 1; i++; unchecked { i++; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe.WithOverflowChecks(true), parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "3").VerifyIL("<top-level-statements-entry-point>", sequencePoints: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName + "." + WellKnownMemberNames.TopLevelStatementsEntryPointMethodName, source: text, expectedIL: @" { // Code size 20 (0x14) .maxstack 2 .locals init (int V_0) //i // sequence point: int i = 1; IL_0000: ldc.i4.1 IL_0001: stloc.0 // sequence point: i++; IL_0002: ldloc.0 IL_0003: ldc.i4.1 IL_0004: add.ovf IL_0005: stloc.0 // sequence point: { IL_0006: nop // sequence point: i++; IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: add IL_000a: stloc.0 // sequence point: } IL_000b: nop // sequence point: System.Console.WriteLine(i); IL_000c: ldloc.0 IL_000d: call ""void System.Console.WriteLine(int)"" IL_0012: nop IL_0013: ret } "); } [Fact] public void UnsafeStatement_01() { var text = @" unsafe { int* p = (int*)0; p++; System.Console.WriteLine((int)p); } "; var comp = CreateCompilation(text, options: TestOptions.UnsafeDebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "4", verify: Verification.Skipped); } [Fact] public void FixedStatement_01() { var text = @" fixed(int *p = &new C().i) {} class C { public int i = 2; } "; var comp = CreateCompilation(text, options: TestOptions.UnsafeDebugExe, parseOptions: DefaultParseOptions); comp.VerifyEmitDiagnostics( // (2,1): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // fixed(int *p = &new C().i) {} Diagnostic(ErrorCode.ERR_UnsafeNeeded, "fixed(int *p = &new C().i) {}").WithLocation(2, 1), // (2,7): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // fixed(int *p = &new C().i) {} Diagnostic(ErrorCode.ERR_UnsafeNeeded, "int *").WithLocation(2, 7), // (2,16): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // fixed(int *p = &new C().i) {} Diagnostic(ErrorCode.ERR_UnsafeNeeded, "&new C().i").WithLocation(2, 16) ); } [Fact] public void LockStatement_01() { var text = @" int i = 1; lock (new object()) { i++; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "2"); } [Fact] public void IfStatement_01() { var text = @" int i = 1; if (i == 1) { i++; } else { i--; } if (i != 2) { i--; } else { i++; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "3"); } [Fact] public void SwitchStatement_01() { var text = @" int i = 1; switch (i) { case 1: i++; break; default: i--; break; } System.Console.WriteLine(i); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "2"); } [Fact] public void TryStatement_01() { var text = @" try { System.Console.Write(1); throw null; } catch { System.Console.Write(2); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "12"); } [Fact] public void Args_01() { var text = @" #nullable enable System.Console.WriteLine(args.Length == 0 ? 0 : -args[0].Length); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "0").VerifyDiagnostics(); var entryPoint = SimpleProgramNamedTypeSymbol.GetSimpleProgramEntryPoint(comp); AssertEntryPointParameter(entryPoint); } [Fact] public void Args_02() { var text1 = @" using System.Linq; _ = from args in new object[0] select args; "; var comp = CreateCompilation(text1, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,10): error CS1931: The range variable 'args' conflicts with a previous declaration of 'args' // _ = from args in new object[0] select args; Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "args").WithArguments("args").WithLocation(3, 10) ); } [Fact] public void Args_03() { var text = @" local(); void local() { System.Console.WriteLine(args[0]); } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Args_03", args: new[] { "Args_03" }).VerifyDiagnostics(); } [Fact] public void Args_04() { var text = @" System.Action lambda = () => System.Console.WriteLine(args[0]); lambda(); "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Args_04", args: new[] { "Args_04" }).VerifyDiagnostics(); } [Fact] public void Span_01() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; Span<int> span = default; _ = new { Span = span }; ", options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (5,11): error CS0828: Cannot assign 'Span<int>' to anonymous type property // _ = new { Span = span }; Diagnostic(ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, "Span = span").WithArguments("System.Span<int>").WithLocation(5, 11) ); } [Fact] public void Span_02() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; Span<int> outer; for (Span<int> inner = stackalloc int[10];; inner = outer) { outer = inner; } ", options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (7,13): error CS8352: Cannot use local 'inner' in this context because it may expose referenced variables outside of their declaration scope // outer = inner; Diagnostic(ErrorCode.ERR_EscapeLocal, "inner").WithArguments("inner").WithLocation(7, 13) ); } [Fact] [WorkItem(1179569, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1179569")] public void Issue1179569() { var text1 = @"Task v0123456789012345678901234567() { Console.Write(""start v0123456789012345678901234567""); await Task.Delay(2 * 1000); Console.Write(""end v0123456789012345678901234567""); } Task On01234567890123456() { return v0123456789012345678901234567(); } string return Task.WhenAll( Task.WhenAll(this.c01234567890123456789012345678.Select(v01234567 => On01234567890123456(v01234567))), Task.WhenAll(this.c01234567890123456789.Select(v01234567 => v01234567.U0123456789012345678901234()))); "; var oldTree = Parse(text: text1, options: TestOptions.RegularDefault); var text2 = @"Task v0123456789012345678901234567() { Console.Write(""start v0123456789012345678901234567""); await Task.Delay(2 * 1000); Console.Write(""end v0123456789012345678901234567""); } Task On01234567890123456() { return v0123456789012345678901234567(); } string[ return Task.WhenAll( Task.WhenAll(this.c01234567890123456789012345678.Select(v01234567 => On01234567890123456(v01234567))), Task.WhenAll(this.c01234567890123456789.Select(v01234567 => v01234567.U0123456789012345678901234()))); "; var newText = Microsoft.CodeAnalysis.Text.StringText.From(text2, System.Text.Encoding.UTF8); using var lexer = new Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.Lexer(newText, TestOptions.RegularDefault); using var parser = new Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax.LanguageParser(lexer, (CSharpSyntaxNode)oldTree.GetRoot(), new[] { new Microsoft.CodeAnalysis.Text.TextChangeRange(new Microsoft.CodeAnalysis.Text.TextSpan(282, 0), 1) }); var compilationUnit = (CompilationUnitSyntax)parser.ParseCompilationUnit().CreateRed(); var tree = CSharpSyntaxTree.Create(compilationUnit, TestOptions.RegularDefault, encoding: System.Text.Encoding.UTF8); Assert.Equal(text2, tree.GetText().ToString()); tree.VerifySource(); var fullParseTree = Parse(text: text2, options: TestOptions.RegularDefault); var nodes1 = tree.GetRoot().DescendantNodesAndTokensAndSelf(descendIntoTrivia: true).ToArray(); var nodes2 = fullParseTree.GetRoot().DescendantNodesAndTokensAndSelf(descendIntoTrivia: true).ToArray(); Assert.Equal(nodes1.Length, nodes2.Length); for (int i = 0; i < nodes1.Length; i++) { var node1 = nodes1[i]; var node2 = nodes2[i]; Assert.Equal(node1.RawKind, node2.RawKind); Assert.Equal(node1.Span, node2.Span); Assert.Equal(node1.FullSpan, node2.FullSpan); Assert.Equal(node1.ToString(), node2.ToString()); Assert.Equal(node1.ToFullString(), node2.ToFullString()); } } [Fact] public void TopLevelLocalReferencedInClass_IOperation() { var comp = CreateCompilation(@" int i = 1; class C { void M() /*<bind>*/{ _ = i; }/*</bind>*/ } ", options: TestOptions.ReleaseExe); var diagnostics = new[] { // (2,5): warning CS0219: The variable 'i' is assigned but its value is never used // int i = 1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(2, 5), // (7,13): error CS8801: Cannot use local variable or local function 'i' declared in a top-level statement in this context. // _ = i; Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "i").WithArguments("i").WithLocation(7, 13) }; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, @" IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '_ = i;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: var, IsInvalid) (Syntax: '_ = i') Left: IDiscardOperation (Symbol: var _) (OperationKind.Discard, Type: var) (Syntax: '_') Right: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'i') ", diagnostics); VerifyFlowGraphForTest<BlockSyntax>(comp, @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '_ = i;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: var, IsInvalid) (Syntax: '_ = i') Left: IDiscardOperation (Symbol: var _) (OperationKind.Discard, Type: var) (Syntax: '_') Right: ILocalReferenceOperation: i (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'i') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "); } [Fact] public void TopLevelLocalFunctionReferencedInClass_IOperation() { var comp = CreateCompilation(@" _ = """"; static void M1() {} void M2() {} class C { void M() /*<bind>*/{ M1(); M2(); }/*</bind>*/ } ", options: TestOptions.ReleaseExe); var diagnostics = new[] { // (3,13): warning CS8321: The local function 'M1' is declared but never used // static void M1() {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "M1").WithArguments("M1").WithLocation(3, 13), // (4,6): warning CS8321: The local function 'M2' is declared but never used // void M2() {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "M2").WithArguments("M2").WithLocation(4, 6), // (9,9): error CS8801: Cannot use local variable or local function 'M1' declared in a top-level statement in this context. // M1(); Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "M1").WithArguments("M1").WithLocation(9, 9), // (10,9): error CS8801: Cannot use local variable or local function 'M2' declared in a top-level statement in this context. // M2(); Diagnostic(ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, "M2").WithArguments("M2").WithLocation(10, 9) }; VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(comp, @" IBlockOperation (2 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ ... }') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M1();') Expression: IInvocationOperation (void M1()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M1()') Instance Receiver: null Arguments(0) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M2();') Expression: IInvocationOperation (void M2()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M2()') Instance Receiver: null Arguments(0) ", diagnostics); VerifyFlowGraphForTest<BlockSyntax>(comp, @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M1();') Expression: IInvocationOperation (void M1()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M1()') Instance Receiver: null Arguments(0) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M2();') Expression: IInvocationOperation (void M2()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M2()') Instance Receiver: null Arguments(0) Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "); } [Fact] public void EmptyStatements_01() { var text = @";"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS8937: At least one top-level statement must be non-empty. // ; Diagnostic(ErrorCode.ERR_SimpleProgramIsEmpty, ";").WithLocation(1, 1) ); } [Fact] public void EmptyStatements_02() { var text = @";; ;; ;"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (1,1): error CS8937: At least one top-level statement must be non-empty. // ;; Diagnostic(ErrorCode.ERR_SimpleProgramIsEmpty, ";").WithLocation(1, 1) ); } [Fact] public void EmptyStatements_03() { var text = @" System.Console.WriteLine(""Hi!""); ;; ; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void EmptyStatements_04() { var text = @" ;; ; System.Console.WriteLine(""Hi!"");"; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void EmptyStatements_05() { var text = @" ; System.Console.WriteLine(""Hi!""); ; "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); CompileAndVerify(comp, expectedOutput: "Hi!"); } [Fact] public void EmptyStatements_06() { var text = @" using System; ; class Program { static void Main(String[] args) {} } "; var comp = CreateCompilation(text, options: TestOptions.DebugExe, parseOptions: DefaultParseOptions); comp.VerifyDiagnostics( // (3,1): error CS8937: At least one top-level statement must be non-empty. // ; Diagnostic(ErrorCode.ERR_SimpleProgramIsEmpty, ";").WithLocation(3, 1), // (7,17): warning CS7022: The entry point of the program is global code; ignoring 'Program.Main(string[])' entry point. // static void Main(String[] args) {} Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("Program.Main(string[])").WithLocation(7, 17) ); } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType.ConstructorSymbol.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 Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed partial class AnonymousTypeManager { /// <summary> /// Represents an anonymous type constructor. /// </summary> private sealed partial class AnonymousTypeConstructorSymbol : SynthesizedMethodBase { private readonly ImmutableArray<ParameterSymbol> _parameters; internal AnonymousTypeConstructorSymbol(NamedTypeSymbol container, ImmutableArray<AnonymousTypePropertySymbol> properties) : base(container, WellKnownMemberNames.InstanceConstructorName) { // Create constructor parameters int fieldsCount = properties.Length; if (fieldsCount > 0) { var paramsArr = ArrayBuilder<ParameterSymbol>.GetInstance(fieldsCount); for (int index = 0; index < fieldsCount; index++) { PropertySymbol property = properties[index]; paramsArr.Add(SynthesizedParameterSymbol.Create(this, property.TypeWithAnnotations, index, RefKind.None, property.Name)); } _parameters = paramsArr.ToImmutableAndFree(); } else { _parameters = ImmutableArray<ParameterSymbol>.Empty; } } public override MethodKind MethodKind { get { return MethodKind.Constructor; } } public override bool ReturnsVoid { get { return true; } } public override RefKind RefKind { get { return RefKind.None; } } public override TypeWithAnnotations ReturnTypeWithAnnotations { get { return TypeWithAnnotations.Create(this.Manager.System_Void); } } public override ImmutableArray<ParameterSymbol> Parameters { get { return _parameters; } } public override bool IsOverride { get { return false; } } internal sealed override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { return false; } internal override bool IsMetadataFinal { get { return false; } } public override ImmutableArray<Location> Locations { get { // The accessor for an anonymous type constructor has the same location as the type. return this.ContainingSymbol.Locations; } } } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed partial class AnonymousTypeManager { /// <summary> /// Represents an anonymous type constructor. /// </summary> private sealed partial class AnonymousTypeConstructorSymbol : SynthesizedMethodBase { private readonly ImmutableArray<ParameterSymbol> _parameters; internal AnonymousTypeConstructorSymbol(NamedTypeSymbol container, ImmutableArray<AnonymousTypePropertySymbol> properties) : base(container, WellKnownMemberNames.InstanceConstructorName) { // Create constructor parameters int fieldsCount = properties.Length; if (fieldsCount > 0) { var paramsArr = ArrayBuilder<ParameterSymbol>.GetInstance(fieldsCount); for (int index = 0; index < fieldsCount; index++) { PropertySymbol property = properties[index]; paramsArr.Add(SynthesizedParameterSymbol.Create(this, property.TypeWithAnnotations, index, RefKind.None, property.Name)); } _parameters = paramsArr.ToImmutableAndFree(); } else { _parameters = ImmutableArray<ParameterSymbol>.Empty; } } public override MethodKind MethodKind { get { return MethodKind.Constructor; } } public override bool ReturnsVoid { get { return true; } } public override RefKind RefKind { get { return RefKind.None; } } public override TypeWithAnnotations ReturnTypeWithAnnotations { get { return TypeWithAnnotations.Create(this.Manager.System_Void); } } public override ImmutableArray<ParameterSymbol> Parameters { get { return _parameters; } } public override bool IsOverride { get { return false; } } internal sealed override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { return false; } internal override bool IsMetadataFinal { get { return false; } } public override ImmutableArray<Location> Locations { get { // The accessor for an anonymous type constructor has the same location as the type. return this.ContainingSymbol.Locations; } } } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/Operations/BranchKind.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.Operations { /// <summary> /// Kind of the branch for an <see cref="IBranchOperation"/> /// </summary> public enum BranchKind { /// <summary> /// Represents unknown branch kind. /// </summary> None = 0x0, /// <summary> /// Represents a continue branch kind. /// </summary> Continue = 0x1, /// <summary> /// Represents a break branch kind. /// </summary> Break = 0x2, /// <summary> /// Represents a goto branch kind. /// </summary> GoTo = 0x3 } }
// Licensed to the .NET Foundation under one or more 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.Operations { /// <summary> /// Kind of the branch for an <see cref="IBranchOperation"/> /// </summary> public enum BranchKind { /// <summary> /// Represents unknown branch kind. /// </summary> None = 0x0, /// <summary> /// Represents a continue branch kind. /// </summary> Continue = 0x1, /// <summary> /// Represents a break branch kind. /// </summary> Break = 0x2, /// <summary> /// Represents a goto branch kind. /// </summary> GoTo = 0x3 } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/CSharp/Test/ProjectSystemShim/CPS/AnalyzersTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework; using Roslyn.Test.Utilities; using Xunit; namespace Roslyn.VisualStudio.CSharp.UnitTests.ProjectSystemShim.CPS { [UseExportProvider] public class AnalyzersTests : TestBase { [WpfFact] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] public async Task RuleSet_GeneralOption_CPS() { var ruleSetFile = Temp.CreateFile().WriteAllText( @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Error"" /> </RuleSet> "); using var environment = new TestEnvironment(); using var project = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test"); var workspaceProject = environment.Workspace.CurrentSolution.Projects.Single(); var options = (CSharpCompilationOptions)workspaceProject.CompilationOptions; Assert.Equal(expected: ReportDiagnostic.Default, actual: options.GeneralDiagnosticOption); project.SetOptions(ImmutableArray.Create($"/ruleset:{ruleSetFile.Path}")); workspaceProject = environment.Workspace.CurrentSolution.Projects.Single(); options = (CSharpCompilationOptions)workspaceProject.CompilationOptions; Assert.Equal(expected: ReportDiagnostic.Error, actual: options.GeneralDiagnosticOption); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] public async Task RuleSet_SpecificOptions_CPS() { var ruleSetFile = Temp.CreateFile().WriteAllText( @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "); using var environment = new TestEnvironment(); using var project = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test"); // Verify SetRuleSetFile updates the ruleset. project.SetOptions(ImmutableArray.Create($"/ruleset:{ruleSetFile.Path}")); // We need to explicitly update the command line arguments so the new ruleset is used to update options. project.SetOptions(ImmutableArray.Create($"/ruleset:{ruleSetFile.Path}")); var ca1012DiagnosticOption = environment.Workspace.CurrentSolution.Projects.Single().CompilationOptions.SpecificDiagnosticOptions["CA1012"]; Assert.Equal(expected: ReportDiagnostic.Error, actual: ca1012DiagnosticOption); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] public async Task RuleSet_PathCanBeFound() { var ruleSetFile = Temp.CreateFile(); using var environment = new TestEnvironment(); ProjectId projectId; using (var project = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test")) { project.SetOptions(ImmutableArray.Create($"/ruleset:{ruleSetFile.Path}")); projectId = project.Id; Assert.Equal(ruleSetFile.Path, environment.Workspace.TryGetRuleSetPathForProject(projectId)); } // Ensure it's still not available after we disposed the project Assert.Null(environment.Workspace.TryGetRuleSetPathForProject(projectId)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework; using Roslyn.Test.Utilities; using Xunit; namespace Roslyn.VisualStudio.CSharp.UnitTests.ProjectSystemShim.CPS { [UseExportProvider] public class AnalyzersTests : TestBase { [WpfFact] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] public async Task RuleSet_GeneralOption_CPS() { var ruleSetFile = Temp.CreateFile().WriteAllText( @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Error"" /> </RuleSet> "); using var environment = new TestEnvironment(); using var project = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test"); var workspaceProject = environment.Workspace.CurrentSolution.Projects.Single(); var options = (CSharpCompilationOptions)workspaceProject.CompilationOptions; Assert.Equal(expected: ReportDiagnostic.Default, actual: options.GeneralDiagnosticOption); project.SetOptions(ImmutableArray.Create($"/ruleset:{ruleSetFile.Path}")); workspaceProject = environment.Workspace.CurrentSolution.Projects.Single(); options = (CSharpCompilationOptions)workspaceProject.CompilationOptions; Assert.Equal(expected: ReportDiagnostic.Error, actual: options.GeneralDiagnosticOption); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] public async Task RuleSet_SpecificOptions_CPS() { var ruleSetFile = Temp.CreateFile().WriteAllText( @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "); using var environment = new TestEnvironment(); using var project = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test"); // Verify SetRuleSetFile updates the ruleset. project.SetOptions(ImmutableArray.Create($"/ruleset:{ruleSetFile.Path}")); // We need to explicitly update the command line arguments so the new ruleset is used to update options. project.SetOptions(ImmutableArray.Create($"/ruleset:{ruleSetFile.Path}")); var ca1012DiagnosticOption = environment.Workspace.CurrentSolution.Projects.Single().CompilationOptions.SpecificDiagnosticOptions["CA1012"]; Assert.Equal(expected: ReportDiagnostic.Error, actual: ca1012DiagnosticOption); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ProjectSystemShims)] public async Task RuleSet_PathCanBeFound() { var ruleSetFile = Temp.CreateFile(); using var environment = new TestEnvironment(); ProjectId projectId; using (var project = await CSharpHelpers.CreateCSharpCPSProjectAsync(environment, "Test")) { project.SetOptions(ImmutableArray.Create($"/ruleset:{ruleSetFile.Path}")); projectId = project.Id; Assert.Equal(ruleSetFile.Path, environment.Workspace.TryGetRuleSetPathForProject(projectId)); } // Ensure it's still not available after we disposed the project Assert.Null(environment.Workspace.TryGetRuleSetPathForProject(projectId)); } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/AccessibilityTests.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.CodeGen; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using System; using Xunit; using Roslyn.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class AccessibilityTests : ExpressionCompilerTestBase { /// <summary> /// Do not allow calling accessors directly. /// (This is consistent with the native EE.) /// </summary> [Fact] public void NotReferencable() { var source = @"class C { object P { get { return null; } } void M() { } }"; ResultProperties resultProperties; string error; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "this.get_P()", resultProperties: out resultProperties, error: out error); Assert.Equal("error CS0571: 'C.P.get': cannot explicitly call operator or accessor", error); } [Fact] public void ParametersAndReturnType_PrivateType() { var source = @"class A { private struct S { } } class B { static T F<T>(T t) { return t; } static void M() { } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "B.M", expr: "F(new A.S())"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 15 (0xf) .maxstack 1 .locals init (A.S V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""A.S"" IL_0008: ldloc.0 IL_0009: call ""A.S B.F<A.S>(A.S)"" IL_000e: ret }"); } [Fact] public void ParametersAndReturnType_DifferentCompilation() { var source = @"class C { static T F<T>(T t) { return t; } static void M() { } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "F(new { P = 1 })"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 12 (0xc) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0006: call ""<anonymous type: int P> C.F<<anonymous type: int P>>(<anonymous type: int P>)"" IL_000b: ret }"); } /// <summary> /// The compiler generates calls to the least derived virtual method while /// the EE calls the most derived method. However, the difference will be /// observable only in cases where C# and CLR diff in how overrides are /// determined (when override differs by ref/out or modopt for instance). /// </summary> [Fact] public void ProtectedAndInternalVirtualCalls() { var source = @"internal class A { protected virtual object M(object o) { return o; } internal virtual object P { get { return null; } } } internal class B : A { protected override object M(object o) { return o; } } internal class C : B { internal override object P { get { return null; } } object M() { return this.M(this.P); } }"; var compilation0 = CreateCompilation( source, options: TestOptions.DebugDll, assemblyName: Guid.NewGuid().ToString("D")); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("this.M(this.P)", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @" { // Code size 13 (0xd) .maxstack 2 .locals init (object V_0) IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: callvirt ""object C.P.get"" IL_0007: callvirt ""object B.M(object)"" IL_000c: ret } "); }); } [Fact] public void InferredTypeArguments_DifferentCompilation() { var source = @"class C { static object F<T, U>(T t, U u) { return t; } static object x = new { A = 1 }; static void M() { } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "F(new { A = 2 }, new { B = 3 })"); // new and existing types testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 18 (0x12) .maxstack 2 IL_0000: ldc.i4.2 IL_0001: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0006: ldc.i4.3 IL_0007: newobj ""<>f__AnonymousType1<int>..ctor(int)"" IL_000c: call ""object C.F<<anonymous type: int A>, <anonymous type: int B>>(<anonymous type: int A>, <anonymous type: int B>)"" IL_0011: 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 Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using System; using Xunit; using Roslyn.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class AccessibilityTests : ExpressionCompilerTestBase { /// <summary> /// Do not allow calling accessors directly. /// (This is consistent with the native EE.) /// </summary> [Fact] public void NotReferencable() { var source = @"class C { object P { get { return null; } } void M() { } }"; ResultProperties resultProperties; string error; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "this.get_P()", resultProperties: out resultProperties, error: out error); Assert.Equal("error CS0571: 'C.P.get': cannot explicitly call operator or accessor", error); } [Fact] public void ParametersAndReturnType_PrivateType() { var source = @"class A { private struct S { } } class B { static T F<T>(T t) { return t; } static void M() { } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "B.M", expr: "F(new A.S())"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 15 (0xf) .maxstack 1 .locals init (A.S V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""A.S"" IL_0008: ldloc.0 IL_0009: call ""A.S B.F<A.S>(A.S)"" IL_000e: ret }"); } [Fact] public void ParametersAndReturnType_DifferentCompilation() { var source = @"class C { static T F<T>(T t) { return t; } static void M() { } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "F(new { P = 1 })"); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 12 (0xc) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0006: call ""<anonymous type: int P> C.F<<anonymous type: int P>>(<anonymous type: int P>)"" IL_000b: ret }"); } /// <summary> /// The compiler generates calls to the least derived virtual method while /// the EE calls the most derived method. However, the difference will be /// observable only in cases where C# and CLR diff in how overrides are /// determined (when override differs by ref/out or modopt for instance). /// </summary> [Fact] public void ProtectedAndInternalVirtualCalls() { var source = @"internal class A { protected virtual object M(object o) { return o; } internal virtual object P { get { return null; } } } internal class B : A { protected override object M(object o) { return o; } } internal class C : B { internal override object P { get { return null; } } object M() { return this.M(this.P); } }"; var compilation0 = CreateCompilation( source, options: TestOptions.DebugDll, assemblyName: Guid.NewGuid().ToString("D")); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("this.M(this.P)", out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @" { // Code size 13 (0xd) .maxstack 2 .locals init (object V_0) IL_0000: ldarg.0 IL_0001: ldarg.0 IL_0002: callvirt ""object C.P.get"" IL_0007: callvirt ""object B.M(object)"" IL_000c: ret } "); }); } [Fact] public void InferredTypeArguments_DifferentCompilation() { var source = @"class C { static object F<T, U>(T t, U u) { return t; } static object x = new { A = 1 }; static void M() { } }"; var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "C.M", expr: "F(new { A = 2 }, new { B = 3 })"); // new and existing types testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 18 (0x12) .maxstack 2 IL_0000: ldc.i4.2 IL_0001: newobj ""<>f__AnonymousType0<int>..ctor(int)"" IL_0006: ldc.i4.3 IL_0007: newobj ""<>f__AnonymousType1<int>..ctor(int)"" IL_000c: call ""object C.F<<anonymous type: int A>, <anonymous type: int B>>(<anonymous type: int A>, <anonymous type: int B>)"" IL_0011: ret }"); } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Test/Completion/CompletionServiceTests.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Completion { [UseExportProvider] public class CompletionServiceTests { [Fact] public async Task TestNuGetCompletionProvider() { var code = @" using System.Diagnostics; class Test { void Method() { Debug.Assert(true, ""$$""); } } "; using var workspace = TestWorkspace.CreateCSharp(code, openDocuments: true); var nugetCompletionProvider = new DebugAssertTestCompletionProvider(); var reference = new MockAnalyzerReference(nugetCompletionProvider); var project = workspace.CurrentSolution.Projects.Single().AddAnalyzerReference(reference); var completionService = project.LanguageServices.GetRequiredService<CompletionService>(); var document = project.Documents.Single(); var caretPosition = workspace.DocumentWithCursor.CursorPosition ?? throw new InvalidOperationException(); var completions = await completionService.GetCompletionsAsync(document, caretPosition); Assert.NotNull(completions); var item = Assert.Single(completions.Items.Where(item => item.ProviderName == typeof(DebugAssertTestCompletionProvider).FullName)); Assert.Equal("Assertion failed", item.DisplayText); } private class MockAnalyzerReference : AnalyzerReference, ICompletionProviderFactory { private readonly CompletionProvider _completionProvider; public MockAnalyzerReference(CompletionProvider completionProvider) { _completionProvider = completionProvider; } public override string FullPath => ""; public override object Id => nameof(MockAnalyzerReference); public override ImmutableArray<DiagnosticAnalyzer> GetAnalyzers(string language) => ImmutableArray<DiagnosticAnalyzer>.Empty; public override ImmutableArray<DiagnosticAnalyzer> GetAnalyzersForAllLanguages() => ImmutableArray<DiagnosticAnalyzer>.Empty; public ImmutableArray<CompletionProvider> GetCompletionProviders() => ImmutableArray.Create(_completionProvider); } private sealed class DebugAssertTestCompletionProvider : CompletionProvider { public DebugAssertTestCompletionProvider() { } public override bool ShouldTriggerCompletion(SourceText text, int caretPosition, CompletionTrigger trigger, OptionSet options) { return trigger.Kind switch { CompletionTriggerKind.Invoke => true, CompletionTriggerKind.InvokeAndCommitIfUnique => true, CompletionTriggerKind.Insertion => trigger.Character == '"', _ => false, }; } public override async Task ProvideCompletionsAsync(CompletionContext context) { var completionItem = CompletionItem.Create(displayText: "Assertion failed", displayTextSuffix: "", rules: CompletionItemRules.Default); context.AddItem(completionItem); context.CompletionListSpan = await GetTextChangeSpanAsync(context.Document, context.CompletionListSpan, context.CancellationToken).ConfigureAwait(false); } private static async Task<TextSpan> GetTextChangeSpanAsync(Document document, TextSpan startSpan, CancellationToken cancellationToken) { var result = startSpan; var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(result.Start); if (syntaxFacts.IsStringLiteral(token) || syntaxFacts.IsVerbatimStringLiteral(token)) { var text = root.GetText(); // Expand selection in both directions until a double quote or any line break character is reached static bool IsWordCharacter(char ch) => !(ch == '"' || TextUtilities.IsAnyLineBreakCharacter(ch)); result = CommonCompletionUtilities.GetWordSpan( text, startSpan.Start, IsWordCharacter, IsWordCharacter, alwaysExtendEndSpan: true); } 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. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Completion { [UseExportProvider] public class CompletionServiceTests { [Fact] public async Task TestNuGetCompletionProvider() { var code = @" using System.Diagnostics; class Test { void Method() { Debug.Assert(true, ""$$""); } } "; using var workspace = TestWorkspace.CreateCSharp(code, openDocuments: true); var nugetCompletionProvider = new DebugAssertTestCompletionProvider(); var reference = new MockAnalyzerReference(nugetCompletionProvider); var project = workspace.CurrentSolution.Projects.Single().AddAnalyzerReference(reference); var completionService = project.LanguageServices.GetRequiredService<CompletionService>(); var document = project.Documents.Single(); var caretPosition = workspace.DocumentWithCursor.CursorPosition ?? throw new InvalidOperationException(); var completions = await completionService.GetCompletionsAsync(document, caretPosition); Assert.NotNull(completions); var item = Assert.Single(completions.Items.Where(item => item.ProviderName == typeof(DebugAssertTestCompletionProvider).FullName)); Assert.Equal("Assertion failed", item.DisplayText); } private class MockAnalyzerReference : AnalyzerReference, ICompletionProviderFactory { private readonly CompletionProvider _completionProvider; public MockAnalyzerReference(CompletionProvider completionProvider) { _completionProvider = completionProvider; } public override string FullPath => ""; public override object Id => nameof(MockAnalyzerReference); public override ImmutableArray<DiagnosticAnalyzer> GetAnalyzers(string language) => ImmutableArray<DiagnosticAnalyzer>.Empty; public override ImmutableArray<DiagnosticAnalyzer> GetAnalyzersForAllLanguages() => ImmutableArray<DiagnosticAnalyzer>.Empty; public ImmutableArray<CompletionProvider> GetCompletionProviders() => ImmutableArray.Create(_completionProvider); } private sealed class DebugAssertTestCompletionProvider : CompletionProvider { public DebugAssertTestCompletionProvider() { } public override bool ShouldTriggerCompletion(SourceText text, int caretPosition, CompletionTrigger trigger, OptionSet options) { return trigger.Kind switch { CompletionTriggerKind.Invoke => true, CompletionTriggerKind.InvokeAndCommitIfUnique => true, CompletionTriggerKind.Insertion => trigger.Character == '"', _ => false, }; } public override async Task ProvideCompletionsAsync(CompletionContext context) { var completionItem = CompletionItem.Create(displayText: "Assertion failed", displayTextSuffix: "", rules: CompletionItemRules.Default); context.AddItem(completionItem); context.CompletionListSpan = await GetTextChangeSpanAsync(context.Document, context.CompletionListSpan, context.CancellationToken).ConfigureAwait(false); } private static async Task<TextSpan> GetTextChangeSpanAsync(Document document, TextSpan startSpan, CancellationToken cancellationToken) { var result = startSpan; var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(result.Start); if (syntaxFacts.IsStringLiteral(token) || syntaxFacts.IsVerbatimStringLiteral(token)) { var text = root.GetText(); // Expand selection in both directions until a double quote or any line break character is reached static bool IsWordCharacter(char ch) => !(ch == '"' || TextUtilities.IsAnyLineBreakCharacter(ch)); result = CommonCompletionUtilities.GetWordSpan( text, startSpan.Start, IsWordCharacter, IsWordCharacter, alwaysExtendEndSpan: true); } return result; } } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Test/Resources/Core/SymbolsTests/TypeForwarders/TypeForwarder2.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. public class Base { }; public class GenericBase<T> { public class NestedGenericBase<T1> { }; };
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. public class Base { }; public class GenericBase<T> { public class NestedGenericBase<T1> { }; };
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Test/Core/Assert/EqualityUnit.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 Roslyn.Test.Utilities { public static class EqualityUnit { public static EqualityUnit<T> Create<T>(T value) { return new EqualityUnit<T>(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. #nullable disable namespace Roslyn.Test.Utilities { public static class EqualityUnit { public static EqualityUnit<T> Create<T>(T value) { return new EqualityUnit<T>(value); } } }
-1