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><new field></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><parameter name></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><result alias></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><new resource></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><new variable></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 <procedureName></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.
<result> = <expression1> AndAlso <expression2></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.
<result> = <expression1> And <expression2></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 {<var> [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.
<result> = <object1> Is <object2></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.
<result> = <object1> IsNot <object2></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(<parameterList>) As IEnumerable(Of <T>)</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.
<result> = <string> Like <pattern></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.
<number1> Mod <number2></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.
<result> = Not <expression></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.
<result> = <expression1> OrElse <expression2></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.
<result> = <expression1> Or <expression2></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.
<result> = TypeOf <objectExpression> Is <typeName></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.
<result> = <expression1> Xor <expression2></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] <procedureName> [(<argumentList>)]</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 {<expression>|<expression1> To <expression2>|[Is] <comparisonOperator> <expression>}</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} <condition></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 <condition>...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 <condition>...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 <condition></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 <condition></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 [<label> | 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(<delegateSignature>)...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 <eventName> [(<argumentList>)]</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 <expression></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 <object>...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 <resource1>[, <resource2>]...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 <typeName> With {[.<property> = <expression>][,...]}</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 <object>...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(<parameterList>) <expression></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(<parameterList>) <expression></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(<parameterList>) <statement></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><namespace name></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><class name></value>
</data>
<data name="interface_name" xml:space="preserve">
<value><interface name></value>
</data>
<data name="module_name" xml:space="preserve">
<value><module name></value>
</data>
<data name="structure_name" xml:space="preserve">
<value><structure name></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><Multiple Types></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 <Obsolete></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><new field></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><parameter name></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><result alias></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><new resource></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><new variable></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 <procedureName></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.
<result> = <expression1> AndAlso <expression2></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.
<result> = <expression1> And <expression2></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 {<var> [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.
<result> = <object1> Is <object2></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.
<result> = <object1> IsNot <object2></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(<parameterList>) As IEnumerable(Of <T>)</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.
<result> = <string> Like <pattern></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.
<number1> Mod <number2></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.
<result> = Not <expression></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.
<result> = <expression1> OrElse <expression2></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.
<result> = <expression1> Or <expression2></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.
<result> = TypeOf <objectExpression> Is <typeName></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.
<result> = <expression1> Xor <expression2></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] <procedureName> [(<argumentList>)]</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 {<expression>|<expression1> To <expression2>|[Is] <comparisonOperator> <expression>}</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} <condition></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 <condition>...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 <condition>...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 <condition></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 <condition></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 [<label> | 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(<delegateSignature>)...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 <eventName> [(<argumentList>)]</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 <expression></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 <object>...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 <resource1>[, <resource2>]...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 <typeName> With {[.<property> = <expression>][,...]}</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 <object>...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(<parameterList>) <expression></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(<parameterList>) <expression></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(<parameterList>) <statement></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><namespace name></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><class name></value>
</data>
<data name="interface_name" xml:space="preserve">
<value><interface name></value>
</data>
<data name="module_name" xml:space="preserve">
<value><module name></value>
</data>
<data name="structure_name" xml:space="preserve">
<value><structure name></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><Multiple Types></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 <Obsolete></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 > Options, Text Editor, C#.</note>
</trans-unit>
<trans-unit id="103">
<source>IntelliSense</source>
<target state="translated">IntelliSense</target>
<note>"IntelliSense" node under Tools > 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 > 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 > 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 > 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 > 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 > 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 > 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 > 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 > 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 > 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 > 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 > 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 > 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 > Options, Text Editor, C#.</note>
</trans-unit>
<trans-unit id="103">
<source>IntelliSense</source>
<target state="translated">IntelliSense</target>
<note>"IntelliSense" node under Tools > 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 > 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 > 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 > 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 > 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 > 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 > 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 > 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 > 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 > 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 > 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 > 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 > 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:<alias>=<file> Reference metadata from the specified assembly file using the given alias (Short form: /r)
/reference:<file list> Reference metadata from the specified assembly files (Short form: /r)
/referencePath:<path list> List of paths where to look for metadata references specified as unrooted paths. (Short form: /rp)
/using:<namespace> Define global namespace using (Short form: /u)
/define:<name>=<value>,... Declare global conditional compilation symbol(s) (Short form: /d)
@<file> Read response file for more options
</source>
<target state="translated">使用方式: vbi [options] [script-file.vbx] [-- script-arguments]
若已指定 script-file 則執行指令碼,否則會啟動互動式 REPL (「讀取、求值、輸出」迴圈)。
選項:
/help 顯示使用方式訊息 (簡短形式: /?)
/version 顯示版本並結束
/reference:<別名>=<檔案> 使用指定別名參考指定組件檔的中繼資料 (簡短形式: /r)
/reference:<檔案清單> 參考指定組件檔的中繼資料 (簡短形式: /r)
/referencePath:<路徑清單> 要尋找指定為非根路徑之中繼資料參考的路徑清單。(簡短形式: /rp)
/using:<命名空間> 定義全域命名空間 using (簡短形式: /u)
/define:<名稱>=<值>,... 宣告全域條件式編譯符號 (簡短形式: /d)
@<檔案> 讀取回應檔以取得更多選項
</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:<alias>=<file> Reference metadata from the specified assembly file using the given alias (Short form: /r)
/reference:<file list> Reference metadata from the specified assembly files (Short form: /r)
/referencePath:<path list> List of paths where to look for metadata references specified as unrooted paths. (Short form: /rp)
/using:<namespace> Define global namespace using (Short form: /u)
/define:<name>=<value>,... Declare global conditional compilation symbol(s) (Short form: /d)
@<file> Read response file for more options
</source>
<target state="translated">使用方式: vbi [options] [script-file.vbx] [-- script-arguments]
若已指定 script-file 則執行指令碼,否則會啟動互動式 REPL (「讀取、求值、輸出」迴圈)。
選項:
/help 顯示使用方式訊息 (簡短形式: /?)
/version 顯示版本並結束
/reference:<別名>=<檔案> 使用指定別名參考指定組件檔的中繼資料 (簡短形式: /r)
/reference:<檔案清單> 參考指定組件檔的中繼資料 (簡短形式: /r)
/referencePath:<路徑清單> 要尋找指定為非根路徑之中繼資料參考的路徑清單。(簡短形式: /rp)
/using:<命名空間> 定義全域命名空間 using (簡短形式: /u)
/define:<名稱>=<值>,... 宣告全域條件式編譯符號 (簡短形式: /d)
@<檔案> 讀取回應檔以取得更多選項
</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.
$ PE L xN ! ' @ @ @ ' W @ ` H .text `.rsrc @
@ @.reloc ` @ B ' H T! @ 0 {
+ *& |